I am learning multithreading and I have found one example which bothers me. (I am not the author of this code).
#include <iostream>
#include <future>
using namespace std;
void testFunc(std::promise<int> &result, std::promise<bool> &done)
{
    // other... 
    result.set_value(10);           
    done.set_value(true); 
    // other.... 
}
int main()
{
    std::promise<int>       resultPromise;
    std::promise<bool>      donePromise;
    std::future<int>    resultFuture = resultPromise.get_future();
    std::future<bool>   doneFuture = donePromise.get_future();
    std::async(std::launch::async, testFunc,
               std::ref(resultPromise), std::ref(donePromise) );    // line A
    bool done = doneFuture.get();                   // line B
    int result_testFunc = resultFuture.get();       // line C
    // do other things with result_testFunc
    return 0;
}
It seems to me that it would be easier to use future which is returned by async. We can return value in testFunc() and then use get() on mentioned future. We don't need to create resultPromise and donePromise.
- Does above snippet presents proper usage of 
futureandpromise? (in theory) - Will 
get(), called on line B, block until the thread functiontestFunc()has completed and exited? 
Aucun commentaire:
Enregistrer un commentaire