dimanche 24 janvier 2021

async and promise - is this correct usage?

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.

  1. Does above snippet presents proper usage of future and promise? (in theory)
  2. Will get(), called on line B, block until the thread function testFunc() has completed and exited?

Aucun commentaire:

Enregistrer un commentaire