{"id":4737,"date":"2016-04-24T07:38:00","date_gmt":"2016-04-24T07:38:00","guid":{"rendered":"https:\/\/www.modernescpp.com\/index.php\/threads-lifetime\/"},"modified":"2016-04-24T07:38:00","modified_gmt":"2016-04-24T07:38:00","slug":"threads-lifetime","status":"publish","type":"post","link":"https:\/\/www.modernescpp.com\/index.php\/threads-lifetime\/","title":{"rendered":"Threads Lifetime"},"content":{"rendered":"<p>The parent has to take care of their child. This simple idea has big consequences for a thread lifetime. The following program starts a thread that displays its ID.<\/p>\n<p><!--more--><br \/>\n<!-- HTML generated using hilite.me --><\/p>\n<div style=\"background: #ffffff none repeat scroll 0% 0%; overflow: auto; width: auto; border-width: 0.1em 0.1em 0.1em 0.8em;\">\n<pre style=\"margin: 0px; line-height: 125%;\"><span style=\"color: #0000ff;\"><span style=\"color: #339966;\">\/\/ threadWithoutJoin.cpp<\/span><br \/><br \/>#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::<span style=\"color: #0000ff;\">thread<\/span> t([]{std::cout &lt;&lt; std::this_thread::get_id() &lt;&lt; std::endl;});\r\n\r\n}\r\n<\/pre>\n<\/div>\n<p>&nbsp;<\/p>\n<p>But the program run results in an unexpected result.<\/p>\n<p>&nbsp;<img loading=\"lazy\" decoding=\"async\" class=\" size-full wp-image-4732\" src=\"https:\/\/www.modernescpp.com\/wp-content\/uploads\/2016\/04\/threadForgetJoin.png\" alt=\"threadForgetJoin\" width=\"541\" height=\"193\" srcset=\"https:\/\/www.modernescpp.com\/wp-content\/uploads\/2016\/04\/threadForgetJoin.png 541w, https:\/\/www.modernescpp.com\/wp-content\/uploads\/2016\/04\/threadForgetJoin-300x107.png 300w\" sizes=\"auto, (max-width: 541px) 100vw, 541px\" \/>&nbsp;<\/p>\n<p>What&#8217;s the reason?<\/p>\n<\/p>\n<h2>join and detach<\/h2>\n<p>The lifetime of the created thread <span style=\"font-family: 'courier new', courier;\">t<\/span> ends with its callable unit. The creator has two choices. First: it waits until its child is done (<span style=\"font-family: courier new,courier;\">t.join()<\/span>). Second: it detaches itself from its child: <span style=\"font-family: courier new,courier;\">t.detach()<\/span>. A thread <span style=\"font-family: 'courier new', courier;\">t<\/span> with the callable unit (you can create threads without a callable unit) is joinable, in case there were no t.join() or t.detach calls to the thread. A joinable thread destructor throws &nbsp;<span style=\"font-family: courier new,courier;\">std::terminate<\/span>&nbsp;&nbsp;exception. Thus, the program terminates. That is the reason, the actual run terminated unexpectedly.<\/p>\n<p>The solution to this problem is simple. By calling <span style=\"font-family: courier new,courier;\">t.join(),<\/span> the program behaves as it should.<\/p>\n<p><!-- HTML generated using hilite.me --><\/p>\n<div style=\"background: #ffffff none repeat scroll 0% 0%; overflow: auto; width: auto; border-width: 0.1em 0.1em 0.1em 0.8em;\">\n<pre style=\"margin: 0px; line-height: 125%;\"><span style=\"color: #0000ff;\"><span style=\"color: #339966;\">\/\/ threadWithJoin.cpp<\/span><br \/><br \/>#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::<span style=\"color: #0000ff;\">thread<\/span> t([]{std::cout &lt;&lt; std::this_thread::get_id() &lt;&lt; std::endl;});\r\n\r\n  t.join(); \r\n\r\n}\r\n<\/pre>\n<\/div>\n<p>&nbsp;<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" class=\" size-full wp-image-4733\" src=\"https:\/\/www.modernescpp.com\/wp-content\/uploads\/2016\/04\/threadJoin.png\" alt=\"threadJoin\" width=\"674\" height=\"194\" srcset=\"https:\/\/www.modernescpp.com\/wp-content\/uploads\/2016\/04\/threadJoin.png 674w, https:\/\/www.modernescpp.com\/wp-content\/uploads\/2016\/04\/threadJoin-300x86.png 300w\" sizes=\"auto, (max-width: 674px) 100vw, 674px\" \/><\/p>\n<h3><span style=\"background-color: #ffffff; color: #3366ff;\"><span style=\"color: #000000;\">A short side note: The challenges of detaching<\/span><br \/><\/span><\/h3>\n<p>Of course, you can use t.detach() instead of t.join() in the program above. The thread t is not joinable anymore, and its destructor didn&#8217;t call <span style=\"font-family: courier new,courier;\">std::terminate<\/span>. Seems terrible because now the program behavior is undefined because the lifetime of the object <span style=\"font-family: courier new,courier;\">std::cout<\/span> is not ensured. The execution of the program goes a little bit odd.<\/p>\n<p><span style=\"background-color: #ffffff; color: #3366ff;\">&nbsp; <\/span><\/p>\n<p><span style=\"color: #3366ff; background-color: #ffffff;\"><img loading=\"lazy\" decoding=\"async\" class=\" size-full wp-image-4734\" src=\"https:\/\/www.modernescpp.com\/wp-content\/uploads\/2016\/04\/threadDetach.png\" alt=\"threadDetach\" width=\"450\" height=\"172\" \/><\/span><\/p>\n<p><span style=\"color: #3366ff;\"><span style=\"color: #000000;\"><span style=\"background-color: #c0c0c0;\"><span style=\"background-color: #ffffff;\"><span style=\"color: #3366ff;\"><span style=\"color: #000000;\">I will elaborate more on this issue in the following article.<\/span><br \/><\/span> <\/span> <\/span> <\/span> <\/span><\/p>\n<h2>Moving threads&nbsp;<\/h2>\n<p>Until now, it was quite easy. But that has not to be forever.<\/p>\n<p>It is impossible to copy a thread (copy semantic); you can only move (<a href=\"http:\/\/thbecker.net\/articles\/rvalue_references\/section_02.html\">move semantic<\/a>) it. If a thread is moved, it&#8217;s a lot more challenging to deal with its lifetime in the right way.<\/p>\n<p><!-- HTML generated using hilite.me --><\/p>\n<div style=\"background: #ffffff none repeat scroll 0% 0%; overflow: auto; width: auto; border-width: 0.1em 0.1em 0.1em 0.8em;\">\n<pre style=\"margin: 0px; line-height: 125%;\"><span style=\"color: #0000ff;\"><span style=\"color: #339966;\">\/\/ threadMoved.cpp<\/span><br \/><br \/>#include &lt;iostream&gt; <\/span>\r\n<span style=\"color: #0000ff;\">#include &lt;thread&gt; <\/span>\r\n<span style=\"color: #0000ff;\">#include &lt;utility&gt;<\/span>\r\n\r\n<span style=\"color: #2b91af;\">int<\/span> main(){ \r\n\r\n  std::<span style=\"color: #0000ff;\">thread<\/span> t([]{std::cout &lt;&lt; std::this_thread::get_id();}); \r\n  std::<span style=\"color: #0000ff;\">thread<\/span> t2([]{std::cout &lt;&lt; std::this_thread::get_id();}); \r\n  \r\n  t= std::move(t2); \r\n  t.join(); \r\n  t2.join(); \r\n\r\n}\r\n<\/pre>\n<\/div>\n<p>&nbsp;<\/p>\n<p>Both threads &#8211; t1 and t2 should do a simple job: print their IDs. In addition, thread t2 will be moved to t: <span style=\"font-family: courier new,courier;\">t= std::move(t2).<\/span> In the end, the <span style=\"font-family: courier new,courier;\">main&nbsp;<\/span>thread takes care of its children and joins them. But wait. That&#8217;s far away from my expectations:<\/p>\n<p>&nbsp;<img loading=\"lazy\" decoding=\"async\" class=\" size-full wp-image-4735\" src=\"https:\/\/www.modernescpp.com\/wp-content\/uploads\/2016\/04\/threadMove.png\" alt=\"threadMove\" width=\"457\" height=\"168\" srcset=\"https:\/\/www.modernescpp.com\/wp-content\/uploads\/2016\/04\/threadMove.png 457w, https:\/\/www.modernescpp.com\/wp-content\/uploads\/2016\/04\/threadMove-300x110.png 300w\" sizes=\"auto, (max-width: 457px) 100vw, 457px\" \/><\/p>\n<p>What is going wrong? We have two issues:<\/p>\n<ol>\n<li>By moving (taking ownership of) &nbsp;the thread t2, t gets a new callable unit, and its destructor will be called. So it&#8217;s destructor calls <span style=\"font-family: courier new,courier;\">std::terminate<\/span>, because it is still joinable.<\/li>\n<li>Thread t2 has no associated callable unit. The invocation of join on a thread without a callable unit leads to the exception <span style=\"font-family: courier new,courier;\">std::system_error<\/span>.<\/li>\n<\/ol>\n<p>I fixed both errors.<\/p>\n<p><!-- HTML generated using hilite.me --><\/p>\n<div style=\"background: #ffffff none repeat scroll 0% 0%; overflow: auto; width: auto; border-width: 0.1em 0.1em 0.1em 0.8em;\">\n<pre style=\"margin: 0px; line-height: 125%;\"><span style=\"color: #0000ff;\"><span style=\"color: #339966;\">\/\/ threadMovedFixed.cpp<\/span><br \/><br \/>#include &lt;iostream&gt; <\/span>\r\n<span style=\"color: #0000ff;\">#include &lt;thread&gt; <\/span>\r\n<span style=\"color: #0000ff;\">#include &lt;utility&gt;<\/span>\r\n\r\n<span style=\"color: #2b91af;\">int<\/span> main(){ \r\n\r\n  std::<span style=\"color: #0000ff;\">thread<\/span> t([]{std::cout &lt;&lt; std::this_thread::get_id() &lt;&lt; std::endl;}); \r\n  std::<span style=\"color: #0000ff;\">thread<\/span> t2([]{std::cout &lt;&lt; std::this_thread::get_id() &lt;&lt; std::endl;}); \r\n  \r\n  t.join();\r\n  t= std::move(t2); \r\n  t.join(); \r\n  \r\n  std::cout &lt;&lt; <span style=\"color: #a31515;\">\"\\n\"<\/span>;\r\n  std::cout &lt;&lt; std::boolalpha &lt;&lt; <span style=\"color: #a31515;\">\"t2.joinable(): \"<\/span> &lt;&lt; t2.joinable() &lt;&lt; std::endl;\r\n\r\n}\r\n<\/pre>\n<\/div>\n<p>&nbsp;<\/p>\n<p>As a result, thread t2 is not joinable anymore.<span style=\"font-family: courier new,courier;\"><\/span><em><\/em><\/p>\n<p><img loading=\"lazy\" decoding=\"async\" class=\" size-full wp-image-4736\" src=\"https:\/\/www.modernescpp.com\/wp-content\/uploads\/2016\/04\/threadMoveRight.png\" alt=\"threadMoveRight\" width=\"455\" height=\"189\" srcset=\"https:\/\/www.modernescpp.com\/wp-content\/uploads\/2016\/04\/threadMoveRight.png 455w, https:\/\/www.modernescpp.com\/wp-content\/uploads\/2016\/04\/threadMoveRight-300x125.png 300w\" sizes=\"auto, (max-width: 455px) 100vw, 455px\" \/><\/p>\n<h2>scoped_thread<\/h2>\n<p>If it&#8217;s too bothersome for you to take care of the lifetime of your threads by hand, you can encapsulate a <span style=\"font-family: courier new,courier;\">std::thread<\/span> in your wrapper class. This class should automatically call join in his destructor. Of course, you can go the other way around and call detach. But you know, there are a few issues with detachment.<\/p>\n<p><a href=\"https:\/\/www.justsoftwaresolutions.co.uk\/blog\/\">Anthony Williams<\/a> created such a valuable class. He called it <span style=\"font-family: courier new,courier;\">scoped_thread<\/span>. The constructor checks that the thread is joinable and joins it finally in the destructor. Because the copy constructor and copy assignment operator is declared <span style=\"font-family: courier new,courier;\">delete<\/span>, objects of <span style=\"font-family: courier new,courier;\">scoped_thread<\/span> can not be copied to or assigned from.<\/p>\n<p><span style=\"color: #3366ff;\"><!-- HTML generated using hilite.me --><\/span><\/p>\n<div style=\"background: #ffffff none repeat scroll 0% 0%; overflow: auto; width: auto; border-width: 0.1em 0.1em 0.1em 0.8em;\">\n<pre style=\"margin: 0px; line-height: 125%;\"><span style=\"color: #0000ff;\"><span style=\"color: #339966;\">\/\/ scoped_thread.cpp<\/span><br \/><br \/>#include &lt;iostream&gt;<\/span>\r\n<span style=\"color: #0000ff;\">#include &lt;thread&gt;<\/span>\r\n<span style=\"color: #0000ff;\">#include &lt;utility&gt;<\/span>\r\n\r\n\r\n<span style=\"color: #0000ff;\">class<\/span> <span style=\"color: #2b91af;\">scoped_thread<\/span>{\r\n  std::<span style=\"color: #0000ff;\">thread<\/span> t;\r\npublic:\r\n  <span style=\"color: #0000ff;\">explicit<\/span> scoped_thread(std::<span style=\"color: #0000ff;\">thread<\/span> t_): t(std::move(t_)){\r\n    <span style=\"color: #0000ff;\">if<\/span> ( !t.joinable()) <span style=\"color: #0000ff;\">throw<\/span> std::logic_error(<span style=\"color: #a31515;\">\"No thread\"<\/span>);\r\n  }\r\n  ~scoped_thread(){\r\n    t.join();\r\n  }\r\n  scoped_thread(scoped_thread&amp;)= <span style=\"color: #0000ff;\">delete<\/span>;\r\n  scoped_thread&amp; <span style=\"color: #0000ff;\">operator<\/span>=(scoped_thread <span style=\"color: #0000ff;\">const<\/span> &amp;)= <span style=\"color: #0000ff;\">delete<\/span>;\r\n};\r\n\r\n<span style=\"color: #2b91af;\">int<\/span> main(){\r\n\r\n  scoped_thread t(std::<span style=\"color: #0000ff;\">thread<\/span>([]{std::cout &lt;&lt; std::this_thread::get_id() &lt;&lt; std::endl;}));\r\n\r\n}\r\n<\/pre>\n<\/div>\n<h2>What&#8217;s next?<\/h2>\n<p>In the <a href=\"https:\/\/www.modernescpp.com\/index.php\/data-for-threads\">next post<\/a>, I will deal with passing data to threads.&nbsp;<strong>(Proofreader Alexey Elymanov)<span id=\"transmark\"><\/span><\/strong><\/p>\n<p>&nbsp;<\/p>\n<p>&nbsp;<\/p>\n<p>&nbsp;<\/p>\n<\/p>\n<p>&nbsp;<\/p>\n<p>&nbsp;<\/p>\n","protected":false},"excerpt":{"rendered":"<p>The parent has to take care of their child. This simple idea has big consequences for a thread lifetime. The following program starts a thread that displays its ID.<\/p>\n","protected":false},"author":21,"featured_media":4732,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[366],"tags":[],"class_list":["post-4737","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-multithreading"],"_links":{"self":[{"href":"https:\/\/www.modernescpp.com\/index.php\/wp-json\/wp\/v2\/posts\/4737","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=4737"}],"version-history":[{"count":0,"href":"https:\/\/www.modernescpp.com\/index.php\/wp-json\/wp\/v2\/posts\/4737\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.modernescpp.com\/index.php\/wp-json\/wp\/v2\/media\/4732"}],"wp:attachment":[{"href":"https:\/\/www.modernescpp.com\/index.php\/wp-json\/wp\/v2\/media?parent=4737"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.modernescpp.com\/index.php\/wp-json\/wp\/v2\/categories?post=4737"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.modernescpp.com\/index.php\/wp-json\/wp\/v2\/tags?post=4737"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}