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

前端 未结 2 1228
花落未央
花落未央 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 11:08

    You don't choose to use a promise instead of the others, you use a promise to fulfill a future in conjunction with the others. The code sample at cppreference.com gives an example of using all four:

    #include 
    #include 
    #include 
     
    int main()
    {
        // future from a packaged_task
        std::packaged_task task([](){ return 7; }); // wrap the function
        std::future f1 = task.get_future();  // get a future
        std::thread(std::move(task)).detach(); // launch on a thread
     
        // future from an async()
        std::future f2 = std::async(std::launch::async, [](){ return 8; });
     
        // future from a promise
        std::promise p;
        std::future f3 = p.get_future();
        std::thread( [](std::promise& p){ p.set_value(9); }, 
                     std::ref(p) ).detach();
     
        std::cout << "Waiting...";
        f1.wait();
        f2.wait();
        f3.wait();
        std::cout << "Done!\nResults are: "
                  << f1.get() << ' ' << f2.get() << ' ' << f3.get() << '\n';
    }
    

    prints

    Waiting...Done!

    Results are: 7 8 9

    Futures are used with all three threads to get their results, and a promise is used with the third one to fulfill a future by means other than a return value. Also, a single thread can fulfill multiple futures with different values via promises, which it can't do otherwise.

    An easy way to think of it is that you can either set a future by returning a value or by using a promise. future has no set method; that functionality is provided by promise. You choose what you need based on what the situation allows.

提交回复
热议问题