{"id":4776,"date":"2016-06-06T20:06:00","date_gmt":"2016-06-06T20:06:00","guid":{"rendered":"https:\/\/www.modernescpp.com\/index.php\/the-special-futures\/"},"modified":"2023-06-26T12:54:56","modified_gmt":"2023-06-26T12:54:56","slug":"the-special-futures","status":"publish","type":"post","link":"https:\/\/www.modernescpp.com\/index.php\/the-special-futures\/","title":{"rendered":"The Special Futures"},"content":{"rendered":"<p>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 <span style=\"font-family: courier new,courier;\">std::async<\/span>. The big charm of<span style=\"font-family: courier new,courier;\"> std::async<\/span> is that the parent has not taken care of his child.<\/p>\n<p><!--more--><\/p>\n<h2>Fire and forget<\/h2>\n<p><span style=\"font-family: courier new,courier;\">std::async<\/span> 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 <span style=\"font-family: courier new,courier;\">std::future<\/span> as a fire-and-forget job. The by <span style=\"font-family: courier new,courier;\">std::async<\/span> created future will be executed just in place. Because the <span style=\"font-family: courier new,courier;\">std::future fut<\/span> is, in this case, not bound to a variable, it&#8217;s not possible to invoke<span style=\"font-family: courier new,courier;\"> fut.get()<\/span> or <span style=\"font-family: courier new,courier;\">fut.wait()<\/span> on the future to get the result of the promise.<\/p>\n<p>Maybe, my last sentences were a bit too confusing. So I&#8217;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<a href=\"https:\/\/www.modernescpp.com\/index.php\/asynchronous-function-calls\"> function calls<\/a>.<\/p>\n<p><!-- HTML generated using hilite.me --><\/p>\n<div style=\"background: #ffffff; overflow: auto; width: auto; gray;border-width: .1em .1em .1em .8em;\">\n<pre style=\"margin: 0; line-height: 125%;\"><span style=\"color: #0000ff;\">auto<\/span> fut= std::async([]{<span style=\"color: #0000ff;\">return<\/span> 2011;});\r\nstd::cout &lt;&lt; fut.get() &lt;&lt; std::endl; <span style=\"color: #008000;\">\/\/\/ 2011<\/span>\r\n  \r\nstd::async(std::launch::async,[]{std::cout &lt;&lt; <span style=\"color: #a31515;\">\"fire and forget\"<\/span> &lt;&lt; std::endl;});  <span style=\"color: #008000;\">\/\/ fire and forget<\/span>\r\n  \r\n<\/pre>\n<\/div>\n<p>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.<\/p>\n<p>&nbsp;<\/p>\n<p><!-- HTML generated using hilite.me --><\/p>\n<div style=\"background: #ffffff; overflow: auto; width: auto; gray;border-width: .1em .1em .1em .8em;\">\n<pre style=\"margin: 0; line-height: 125%;\"><span style=\"color: #008000;\">\/\/ async.cpp<\/span>\r\n\r\n<span style=\"color: #0000ff;\">#include &lt;iostream&gt;<\/span>\r\n<span style=\"color: #0000ff;\">#include &lt;future&gt;<\/span>\r\n\r\n<span style=\"color: #2b91af;\">int<\/span> main() {\r\n\r\n    std::cout &lt;&lt; std::endl;\r\n    std::async([](){std::cout &lt;&lt; <span style=\"color: #a31515;\">\"fire and forget\"<\/span> &lt;&lt; std::endl;});\r\n    std::cout &lt;&lt; <span style=\"color: #a31515;\">\"main done \"<\/span> &lt;&lt; std::endl;\r\n}\r\n  \r\n<\/pre>\n<\/div>\n<p>&nbsp;<\/p>\n<p>Without further ado, the output.<\/p>\n<p>&nbsp;<img loading=\"lazy\" decoding=\"async\" class=\" size-full wp-image-4773\" src=\"https:\/\/www.modernescpp.com\/wp-content\/uploads\/2016\/06\/async.PNG\" alt=\"async\" width=\"500\" height=\"124\" srcset=\"https:\/\/www.modernescpp.com\/wp-content\/uploads\/2016\/06\/async.PNG 625w, https:\/\/www.modernescpp.com\/wp-content\/uploads\/2016\/06\/async-300x74.png 300w\" sizes=\"auto, (max-width: 500px) 100vw, 500px\" \/><\/p>\n<p>&nbsp;<\/p>\n<p>The praise for the behavior is high. Too high.<\/p>\n<\/p>\n<h2>One after another<\/h2>\n<p>The future that is created by <span style=\"font-family: courier new,courier;\">std::async<\/span>, 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.<\/p>\n<p>&nbsp;<\/p>\n<p><!-- HTML generated using hilite.me --><\/p>\n<div style=\"background: #ffffff; overflow: auto; width: auto; gray;border-width: .1em .1em .1em .8em;\">\n<table>\n<tbody>\n<tr>\n<td>\n<pre style=\"margin: 0; line-height: 125%;\"> 1\r\n 2\r\n 3\r\n 4\r\n 5\r\n 6\r\n 7\r\n 8\r\n 9\r\n10\r\n11\r\n12\r\n13\r\n14\r\n15\r\n16\r\n17\r\n18\r\n19\r\n20\r\n21\r\n22\r\n23\r\n24<\/pre>\n<\/td>\n<td>\n<pre style=\"margin: 0; line-height: 125%;\"><span style=\"color: #008000;\">\/\/ blocking.cpp<\/span>\r\n\r\n<span style=\"color: #0000ff;\">#include &lt;chrono&gt;<\/span>\r\n<span style=\"color: #0000ff;\">#include &lt;future&gt;<\/span>\r\n<span style=\"color: #0000ff;\">#include &lt;iostream&gt;<\/span>\r\n<span style=\"color: #0000ff;\">#include &lt;thread&gt;<\/span>\r\n\r\n<span style=\"color: #2b91af;\">int<\/span> main(){\r\n\r\n  std::cout &lt;&lt; std::endl;\r\n\r\n  std::async(std::launch::async,[]{\r\n    std::this_thread::sleep_for(std::chrono::seconds(2));\r\n    std::cout &lt;&lt; <span style=\"color: #a31515;\">\"first thread\"<\/span> &lt;&lt; std::endl;\r\n    });\r\n    \r\n  std::async(std::launch::async,[]{\r\n    std::this_thread::sleep_for(std::chrono::seconds(1));  \r\n    std::cout &lt;&lt; <span style=\"color: #a31515;\">\"second thread\"<\/span> &lt;&lt; std::endl;}\r\n    );\r\n  \r\n  std::cout &lt;&lt; <span style=\"color: #a31515;\">\"main thread\"<\/span> &lt;&lt; std::endl;  \r\n\r\n}\r\n<\/pre>\n<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<\/div>\n<p>&nbsp;<\/p>\n<p>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.<\/p>\n<p>&nbsp;<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" class=\" size-full wp-image-4774\" src=\"https:\/\/www.modernescpp.com\/wp-content\/uploads\/2016\/06\/blocking.PNG\" alt=\"blocking\" width=\"500\" height=\"137\" srcset=\"https:\/\/www.modernescpp.com\/wp-content\/uploads\/2016\/06\/blocking.PNG 625w, https:\/\/www.modernescpp.com\/wp-content\/uploads\/2016\/06\/blocking-300x82.png 300w\" sizes=\"auto, (max-width: 500px) 100vw, 500px\" \/><\/p>\n<p>I want to stress this point once more. Although I create in the <span style=\"font-family: courier new,courier;\">main<\/span>-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.<\/p>\n<p>The key issue is that the by <span style=\"font-family: courier new,courier;\">std::async<\/span> 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.<\/p>\n<p>&nbsp;&nbsp;<\/p>\n<p><!-- HTML generated using hilite.me --><\/p>\n<div style=\"background: #ffffff; overflow: auto; width: auto; gray;border-width: .1em .1em .1em .8em;\">\n<table>\n<tbody>\n<tr>\n<td>\n<pre style=\"margin: 0; line-height: 125%;\"> 1\r\n 2\r\n 3\r\n 4\r\n 5\r\n 6\r\n 7\r\n 8\r\n 9\r\n10\r\n11\r\n12\r\n13\r\n14\r\n15\r\n16\r\n17\r\n18\r\n19\r\n20\r\n21\r\n22\r\n23\r\n24<\/pre>\n<\/td>\n<td>\n<pre style=\"margin: 0; line-height: 125%;\"><span style=\"color: #008000;\">\/\/ notBlocking.cpp<\/span>\r\n\r\n<span style=\"color: #0000ff;\">#include &lt;chrono&gt;<\/span>\r\n<span style=\"color: #0000ff;\">#include &lt;future&gt;<\/span>\r\n<span style=\"color: #0000ff;\">#include &lt;iostream&gt;<\/span>\r\n<span style=\"color: #0000ff;\">#include &lt;thread&gt;<\/span>\r\n\r\n<span style=\"color: #2b91af;\">int<\/span> main(){\r\n\r\n  std::cout &lt;&lt; std::endl;\r\n\r\n  <span style=\"color: #0000ff;\">auto<\/span> first= std::async(std::launch::async,[]{\r\n    std::this_thread::sleep_for(std::chrono::seconds(2));\r\n    std::cout &lt;&lt; <span style=\"color: #a31515;\">\"first thread\"<\/span> &lt;&lt; std::endl;\r\n    });\r\n    \r\n  <span style=\"color: #0000ff;\">auto<\/span> second= std::async(std::launch::async,[]{\r\n    std::this_thread::sleep_for(std::chrono::seconds(1));  \r\n    std::cout &lt;&lt; <span style=\"color: #a31515;\">\"second thread\"<\/span> &lt;&lt; std::endl;}\r\n    );\r\n  \r\n  std::cout &lt;&lt; <span style=\"color: #a31515;\">\"main thread\"<\/span> &lt;&lt; std::endl;  \r\n\r\n}\r\n<\/pre>\n<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<\/div>\n<p>&nbsp;<\/p>\n<p>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 <span style=\"font-family: courier new,courier;\">main<\/span> 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.<\/p>\n<p>&nbsp;<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" class=\" size-full wp-image-4775\" src=\"https:\/\/www.modernescpp.com\/wp-content\/uploads\/2016\/06\/notBlocking.PNG\" alt=\"notBlocking\" width=\"500\" height=\"137\" srcset=\"https:\/\/www.modernescpp.com\/wp-content\/uploads\/2016\/06\/notBlocking.PNG 625w, https:\/\/www.modernescpp.com\/wp-content\/uploads\/2016\/06\/notBlocking-300x82.png 300w\" sizes=\"auto, (max-width: 500px) 100vw, 500px\" \/>&nbsp;<\/p>\n<h2>It&#8217;s not so bad<\/h2>\n<p>I have to admit, my usage of <span style=\"font-family: courier new,courier;\">std::async<\/span> creates futures very contrived. At first, the futures were not bound to a variable. Second, I didn&#8217;t use the future to pick up the result from the promise by a <span style=\"font-family: courier new,courier;\">get<\/span> or <span style=\"font-family: courier new,courier;\">wait<\/span> call. Precisely in that situation, we can observe the strange behavior that the future blocks in its destructor.<\/p>\n<p>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&#8217;t hold for futures, which are created by <span style=\"font-family: courier new,courier;\">std::packaged_task<\/span> or <span style=\"font-family: courier new,courier;\">std::promise.<\/span><\/p>\n<h2>What&#8217;s next?<\/h2>\n<p>I guess you know it. I&#8217;m not a big fan of <a href=\"https:\/\/www.modernescpp.com\/index.php\/condition-variables\">condition variable<\/a>s. 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 <a href=\"https:\/\/www.modernescpp.com\/index.php\/thread-synchronization-with-condition-variables-or-tasks\">next post. <\/a>(<strong>Proofreader Alexey Elymanov<\/strong>)<\/p>\n<p>&nbsp;<\/p>\n<p>&nbsp;<\/p><\/p>\n","protected":false},"excerpt":{"rendered":"<p>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.<\/p>\n","protected":false},"author":21,"featured_media":4773,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[366],"tags":[524,446],"class_list":["post-4776","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-multithreading","tag-async","tag-tasks"],"_links":{"self":[{"href":"https:\/\/www.modernescpp.com\/index.php\/wp-json\/wp\/v2\/posts\/4776","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.modernescpp.com\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.modernescpp.com\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.modernescpp.com\/index.php\/wp-json\/wp\/v2\/users\/21"}],"replies":[{"embeddable":true,"href":"https:\/\/www.modernescpp.com\/index.php\/wp-json\/wp\/v2\/comments?post=4776"}],"version-history":[{"count":1,"href":"https:\/\/www.modernescpp.com\/index.php\/wp-json\/wp\/v2\/posts\/4776\/revisions"}],"predecessor-version":[{"id":6974,"href":"https:\/\/www.modernescpp.com\/index.php\/wp-json\/wp\/v2\/posts\/4776\/revisions\/6974"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.modernescpp.com\/index.php\/wp-json\/wp\/v2\/media\/4773"}],"wp:attachment":[{"href":"https:\/\/www.modernescpp.com\/index.php\/wp-json\/wp\/v2\/media?parent=4776"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.modernescpp.com\/index.php\/wp-json\/wp\/v2\/categories?post=4776"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.modernescpp.com\/index.php\/wp-json\/wp\/v2\/tags?post=4776"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}