Why the block future :: wait () does not work

#include <iostream> #include <string> #include <thread> #include <future> int main() { auto pms = std::promise<std::string>(); auto ftr = pms.get_future(); std::thread([&](){pms.set_value("hello world");}); ftr.wait(); std::cout << ftr.get() << std::endl; return 0; } 

According to this link , std::future::wait blocked until the result is available.

However, the above code cannot print anything. Obviously, the main thread ended before the pms.set_value stream pms.set_value .

Why is the ftr.wait() block not blocking?

+6
source share
2 answers

The problem is not that std::future::wait not blocked. The real problem is that you have a race condition between the thread you spawned, execute it, and destroying the std::thread (temporary) object in the main thread.

Because of this, abort is called in the std::thread destructor if the thread is still connecting.

Work code:

 #include <iostream> #include <string> #include <thread> #include <future> #include <chrono> int main() { auto pms = std::promise<std::string>(); auto ftr = pms.get_future(); std::thread thread ([&](){pms.set_value("hello world");}); ftr.wait(); std::cout << ftr.get() << std::endl; thread.join (); return 0; } 

Please note that if you do not explicitly join the thread , you will still have the same race condition (since it is possible that main can do its job faster than thread can clear itself.

Demo of a working example: here .

+9
source

Alternatively, you can detach the thread and use promise::set_value_at_thread_exit rather than set_value

 #include <iostream> #include <string> #include <thread> #include <future> #include <chrono> int main() { auto pms = std::promise<std::string>(); auto ftr = pms.get_future(); std::thread([&](){pms.set_value_at_thread_exit("hello world");}).detach(); ftr.wait(); std::cout << ftr.get() << std::endl; return 0; } 
0
source

Source: https://habr.com/ru/post/1013220/


All Articles