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

前端 未结 2 1219
花落未央
花落未央 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<int> p;
    std::future<int> f = p.get_future();
    std::future<void> 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();
    }
    
    0 讨论(0)
  • 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 <iostream>
    #include <future>
    #include <thread>
     
    int main()
    {
        // future from a packaged_task
        std::packaged_task<int()> task([](){ return 7; }); // wrap the function
        std::future<int> f1 = task.get_future();  // get a future
        std::thread(std::move(task)).detach(); // launch on a thread
     
        // future from an async()
        std::future<int> f2 = std::async(std::launch::async, [](){ return 8; });
     
        // future from a promise
        std::promise<int> p;
        std::future<int> f3 = p.get_future();
        std::thread( [](std::promise<int>& 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.

    0 讨论(0)
提交回复
热议问题