I have a below code where I am using future and promise to get return value from a function. Below is the code:
void myfunction2(string msg, std::promise<std::string> && prms)
{
prms.set_value(msg);
}
int main()
{
std::promise<std::string> prms;
std::future<std::string> ftr = prms.get_future();
while (1)
{
thread t1(myfunction2, "Hello thread", std::move(prms));
cout << "Main loop" << endl;
std::string str = ftr.get();
std::cout << str << std::endl;
t1.join();
Sleep(2000);
}
}
It outputs below:
Main loop
Hello thread
Main loop
As it is inside the while(1) so when the controls comes back to std::string str = ftr.get(); it throws some exception
Unhandled exception at 0x00007FFDD0F1A388 in Testcode.exe: Microsoft C++ exception: std::future_error at memory location 0x00000003FDCFF740.
If I run it without while(1) this will work but I actually need to run it inside the `while(1) loop. How can I resolve this issue.
You can only set the value of a promise once. To use loop in your program, relegate the promise and future variables within the scope of the loop, like so:
int main()
{
int i = 0;
while (1)
{
std::promise<std::string> prms;
std::future<std::string> ftr = prms.get_future();
thread t1(myfunction2, "Hello thread", std::move(prms));
cout << "Main loop" << endl;
std::string str = ftr.get();
std::cout << str << std::endl;
t1.join();
Sleep(2000);
if (++i > 3) break; // no infinite loop
}
}
Edited: In your code, other threads will not spawn till the first one joins and so on. Code snippet edited to allow concurrent execution. Here all the threads are spawn to allow parallel execution and later joined collectively at the end.
int main()
{
std::vector<std::pair<std::thread, std::future<std::string>>> threads;
for (int i = 0; i < 5; i++)
{
std::promise<std::string> prms;
std::future<std::string> fut = prms.get_future();
thread th(myfunction2, "Hello thread", std::move(prms));
threads.push_back(make_pair(move(th), move(fut)));
}
for (auto& e : threads)
{
auto th = move(e.first);
auto fut = move(e.second);
std::string str = fut.get();
std::cout << str << std::endl;
th.join();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With