Quantcast
Channel: Parallel Computing in C++ and Native Code forum
Viewing all articles
Browse latest Browse all 856

How to poll an std::future to see if it's result is available?

$
0
0

In the code snippet below I'm attempting to manually associate a promise set on one thread with a future checked on another. I then attempt to poll the future to see if it is ready but the loop never terminates. The call to future::wait_for() always returns future_status::deferred. If I remove the wait_for and instead loop for some fixed number of iterations with a sleep_for in the while loop I can get() the future as expected and the function exits normally.

Am I misunderstanding the correct usage of wait_for()? Is there any other way to poll for a future becoming available without blocking on a get() call?

#include <chrono>
#include <thread>
#include <future>
#include <iostream>

using namespace std;
using namespace std::chrono;

void DoSomeWork(int numIters, promise<int>& ret) { int it = 0; for ( ; it < numIters; ++it) { cout << "Thread " << this_thread::get_id() << " working..." << endl; this_thread::sleep_for(milliseconds(1000)); } ret.set_value(it); } void TestPromise() { int its = 10; promise<int> aPromise; thread aThread(DoSomeWork, its, ref(aPromise)); auto aFuture = aPromise.get_future(); while (aFuture.wait_for(milliseconds(100)) != future_status::ready) { cout << "Thread " << this_thread::get_id() << " waiting..." << endl; } cout << "Work iterations: " << aFuture.get(); aThread.join(); }

int main()
{
    TestPromise();
    return 0;
}




Viewing all articles
Browse latest Browse all 856

Latest Images

Trending Articles



Latest Images

<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>