When is it a good idea to use std::promise over the other std::thread mechanisms?

前端 未结 2 1227
花落未央
花落未央 2020-12-23 10:53

I am trying to establish some heuristics to help me decide the appropriate std::thread class to use.

As I understand it, from highest level (simplest to

2条回答
  •  独厮守ぢ
    2020-12-23 10:54

    When you have two levels of async, you need to use a promise. Eg:

    void fun()
    {
    std::promise p;
    std::future f = p.get_future();
    std::future f2;
    auto f3 = std::async([&]{
       // Do some other computation
       f2 = std::async([&]{ p.set_value(42);});
       // Do some other work
    });
       // Do some other work
       // Now wait for the result of async work;
    std::cout << f.get();
       // Do some other work again 
    // Wait for async threads to complete
    f3.wait();
    f2.wait();
    }
    

提交回复
热议问题