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.
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.
Without further ado, the output.
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.
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.
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.
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, Kris Kafka, 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, Matthieu Bolt, Stephen Kelley, Kyle Dean, Tusar Palauri, Dmitry Farberov, 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, moon, and Philipp Lenk.
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|
I’m happy to give online seminars or face-to-face seminars worldwide. Please call me if you have any questions.
- Embedded Programmierung mit modernem C++ 12.12.2023 – 14.12.2023 (Präsenzschulung, Termingarantie)
Standard Seminars (English/German)
Here is a compilation of my standard seminars. These seminars are only meant to give you a first orientation.
- C++ – The Core Language
- C++ – The Standard Library
- C++ – Compact
- C++11 and C++14
- Concurrency with Modern C++
- Design Pattern and Architectural Pattern with C++
- Embedded Programming with Modern C++
- Generic Programming (Templates) with C++
- Clean Code with Modern C++
- Phone: +49 7472 917441
- Mobil:: +49 176 5506 5086
- Mail: schulung@ModernesCpp.de
- German Seminar Page: www.ModernesCpp.de
- Mentoring Page: www.ModernesCpp.org
Modernes C++ Mentoring,