The Special Futures
The parent of a thread has to take care of their child. The parent can wait until his child is done or detach himself from his child. But that is not new. But that will not hold for std::async. The big charm of std::async is that the parent has not taken care of his child.
Fire and forget
std::async creates special futures. These futures wait in their destructor until the work of the associated promise is done. That is why the creator has not taken care of their child. But it gets even better. You can execute a std::future as a fire-and-forget job. The by std::async created future will be executed just in place. Because the std::future fut is, in this case, not bound to a variable, it’s not possible to invoke fut.get() or fut.wait() on the future to get the result of the promise.
Maybe, my last sentences were a bit too confusing. So I’ll compare an ordinary future with a fire-and-forget future. It is necessary for fire-and-forget futures that the promise runs in a separate thread to start immediately with its work. The std::launch::async policy does this. You can read the details of the launch policy in the post-asynchronous function calls.
auto fut= std::async([]{return 2011;}); std::cout << fut.get() << std::endl; /// 2011 std::async(std::launch::async,[]{std::cout << "fire and forget" << std::endl;}); // fire and forget
The fire-and-forget futures have a bag charm. They will run in place and execute their work package without the creator taking care of them. The simple example shows the described behavior.
// async.cpp #include <iostream> #include <future> int main() { std::cout << std::endl; std::async([](){std::cout << "fire and forget" << std::endl;}); std::cout << "main done " << std::endl; }
Without further ado, the output.
Modernes C++ Mentoring
Do you want to stay informed: Subscribe.
The praise for the behavior is high. Too high.
One after another
The future that is created by std::async, waits in its destructor until its work is done. Another word for waiting is blocking. The future blocks the progress of the program in its destructor. This becomes obvious in case you use fire-and-forget futures.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
// blocking.cpp #include <chrono> #include <future> #include <iostream> #include <thread> int main(){ std::cout << std::endl; std::async(std::launch::async,[]{ std::this_thread::sleep_for(std::chrono::seconds(2)); std::cout << "first thread" << std::endl; }); std::async(std::launch::async,[]{ std::this_thread::sleep_for(std::chrono::seconds(1)); std::cout << "second thread" << std::endl;} ); std::cout << "main thread" << std::endl; } |
The program executes two promises in its own thread. The resulting futures are fire-and-forget futures. These futures block in their destructor until the associated promise is done. The result is that the promise will be executed with high probability in that sequence in which you find them in the source code. That is exactly what you see in the output of the program.
I want to stress this point once more. Although I create in the main-thread two promises, which are executed in separate threads, the threads run in sequence one after the other. That is why the thread with the more time-consuming work package (line 12) finishes first. Wow, that was disappointing. Instead of three threads running concurrently, each thread will be executed after another.
The key issue is that the by std::async created thread is waiting in its destructor until the associated promise is made, which can not be solved. The problem can only be mitigated. In case you bind the future to a variable, the blocking will take place at the time point when the variable goes out of scope. That is the behavior you can observe in the following example.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
// notBlocking.cpp #include <chrono> #include <future> #include <iostream> #include <thread> int main(){ std::cout << std::endl; auto first= std::async(std::launch::async,[]{ std::this_thread::sleep_for(std::chrono::seconds(2)); std::cout << "first thread" << std::endl; }); auto second= std::async(std::launch::async,[]{ std::this_thread::sleep_for(std::chrono::seconds(1)); std::cout << "second thread" << std::endl;} ); std::cout << "main thread" << std::endl; } |
Now, the output of the program matches our intuition because the three threads are executed in parallel. The future first (line 12) and second (line 17) are valid until the end of the main function (line 24). So, the destructor will perhaps block at this time point. The result is that the threads with the smallest work package are the fastest ones.
It’s not so bad
I have to admit, my usage of std::async creates futures very contrived. At first, the futures were not bound to a variable. Second, I didn’t use the future to pick up the result from the promise by a get or wait call. Precisely in that situation, we can observe the strange behavior that the future blocks in its destructor.
The key reason for these posts was to show that a fire-and-forget future, which is not bound to a variable, must be handled carefully. But this point doesn’t hold for futures, which are created by std::packaged_task or std::promise.
What’s next?
I guess you know it. I’m not a big fan of condition variables. So I want to compare condition variables with tasks to synchronize threads. Because I believe tasks are often the less error-prone and therefore the better choice. So, stay tuned for the next post. (Proofreader Alexey Elymanov)
Thanks a lot to my Patreon Supporters: Matt Braun, Roman Postanciuc, Tobias Zindl, G Prvulovic, Reinhold Dröge, Abernitzke, Frank Grimm, Sakib, Broeserl, António Pina, Sergey Agafyin, Андрей Бурмистров, Jake, GS, Lawton Shoemake, Jozo Leko, John Breland, Venkat Nandam, Jose Francisco, Douglas Tinkham, Kuchlong Kuchlong, Robert Blanch, Truels Wissneth, Mario Luoni, Friedrich Huber, lennonli, Pramod Tikare Muralidhara, Peter Ware, Daniel Hufschläger, Alessandro Pezzato, Bob Perry, Satish Vangipuram, Andi Ireland, Richard Ohnemus, Michael Dunsky, Leo Goodstadt, John Wiederhirn, Yacob Cohen-Arazi, Florian Tischler, Robin Furness, Michael Young, Holger Detering, Bernd Mühlhaus, Stephen Kelley, Kyle Dean, Tusar Palauri, Juan Dent, George Liao, Daniel Ceperley, Jon T Hess, Stephen Totten, Wolfgang Fütterer, Matthias Grün, Phillip Diekmann, Ben Atakora, Ann Shatoff, Rob North, Bhavith C Achar, Marco Parri Empoli, Philipp Lenk, Charles-Jianye Chen, Keith Jeffery, Matt Godbolt, and Honey Sukesan.
Thanks, in particular, to Jon Hess, Lakshman, Christian Wittenhorst, Sherhy Pyton, Dendi Suhubdy, Sudhakar Belagurusamy, Richard Sargeant, Rusty Fleming, John Nebel, Mipko, Alicja Kaminska, Slavko Radman, and David Poole.
My special thanks to Embarcadero | |
My special thanks to PVS-Studio | |
My special thanks to Tipi.build | |
My special thanks to Take Up Code | |
My special thanks to SHAVEDYAKS |
Modernes C++ GmbH
Modernes C++ Mentoring (English)
Rainer Grimm
Yalovastraße 20
72108 Rottenburg
Mail: schulung@ModernesCpp.de
Mentoring: www.ModernesCpp.org
Modernes C++ Mentoring,
Leave a Reply
Want to join the discussion?Feel free to contribute!