{"id":4731,"date":"2016-04-26T19:40:00","date_gmt":"2016-04-26T19:40:00","guid":{"rendered":"https:\/\/www.modernescpp.com\/index.php\/data-for-threads\/"},"modified":"2016-04-26T19:40:00","modified_gmt":"2016-04-26T19:40:00","slug":"data-for-threads","status":"publish","type":"post","link":"https:\/\/www.modernescpp.com\/index.php\/data-for-threads\/","title":{"rendered":"Thread Arguments"},"content":{"rendered":"<p>A thread gets its data by copy or by reference. By default, you should use by copy. Why? In case your thread gets its data by reference, you have to be extremely careful about the lifetime of the arguments.<\/p>\n<p><!--more--><\/p>\n<p>&nbsp;<\/p>\n<h2>Thread arguments<\/h2>\n<p>A thread is a <a href=\"https:\/\/en.wikipedia.org\/wiki\/Variadic_template\">variadic template<\/a>. So it can get an arbitrary number of arguments.<\/p>\n<p>But now to the difference between getting the argument by copy or by reference.<\/p>\n<p>&nbsp;<\/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%;\">std::string s{<span style=\"color: #a31515;\">\"C++11\"<\/span>}\r\n\r\nstd::<span style=\"color: #0000ff;\">thread<\/span> t([=]{ std::cout &lt;&lt; s &lt;&lt; std::endl;});\r\nt.join();\r\n\r\nstd::<span style=\"color: #0000ff;\">thread<\/span> t2([&amp;]{ std::cout &lt;&lt; s &lt;&lt; std::endl;});\r\nt2.detach()\r\n<\/pre>\n<\/div>\n<p>&nbsp;<\/p>\n<p>Precisely said, it is not the thread that gets the arguments in this example, but the lambda function. But that makes no difference for my argumentation. So the first thread t1 gets its data per copy (<span style=\"font-family: courier new,courier;\">[=]<\/span>), and the second thread t2 gets its data by reference (<span style=\"font-family: courier new,courier;\">[&amp;]<\/span>).<\/p>\n<p>What dangers are hidden in these lines? Thread t2 gets its string s by reference and is afterward detached from the lifetime of its creator. On the one hand, the lifetime of the string is bound to the lifetime of the invocation context, and on the other hand, the lifetime of the global object<span style=\"font-family: courier new,courier;\"> std::cout<\/span> is bound to the lifetime of<span style=\"font-family: courier new,courier;\"> the main <\/span>thread. So it may happen that the lifetime of the string s or the lifetime of <span style=\"font-family: courier new,courier;\">std::cout<\/span> is shorter than the lifetime of the thread t2. Now we are deep in the area of undefined behavior.<\/p>\n<\/p>\n<p>Not convinced? Let&#8217;s have a closer look, what undefined behavior may look like.<\/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\r\n25\r\n26\r\n27\r\n28\r\n29\r\n30\r\n31\r\n32\r\n33<\/pre>\n<\/td>\n<td>\n<pre style=\"margin: 0; line-height: 125%;\"><span style=\"color: #008000;\">\/\/ threadArguments.cpp<\/span>\r\n\r\n<span style=\"color: #0000ff;\">#include &lt;chrono&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: #0000ff;\">class<\/span> <span style=\"color: #2b91af;\">Sleeper<\/span>{\r\n  public:\r\n    Sleeper(<span style=\"color: #2b91af;\">int<\/span>&amp; i_):i{i_}{};\r\n    <span style=\"color: #2b91af;\">void<\/span> operator() (<span style=\"color: #2b91af;\">int<\/span> k){\r\n      <span style=\"color: #0000ff;\">for<\/span> (<span style=\"color: #2b91af;\">unsigned<\/span> <span style=\"color: #2b91af;\">int<\/span> j= 0; j &lt;= 5; ++j){\r\n        std::this_thread::sleep_for(std::chrono::milliseconds(100));\r\n        i += k;\r\n      }\r\n      std::cout &lt;&lt; std::this_thread::get_id() &lt;&lt; std::endl;\r\n    }\r\n  private:\r\n    <span style=\"color: #2b91af;\">int<\/span>&amp; i;\r\n};\r\n\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: #2b91af;\">int<\/span> valSleeper= 1000;\r\n  std::<span style=\"color: #0000ff;\">thread<\/span> t(Sleeper(valSleeper),5);\r\n  t.detach();\r\n  std::cout &lt;&lt; <span style=\"color: #a31515;\">\"valSleeper = \"<\/span> &lt;&lt; valSleeper &lt;&lt; std::endl;\r\n\r\n  std::cout &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 question is, which value valSleeper has in line 26 <span style=\"font-family: courier new,courier;\">valSleeper<\/span> as a global variable? The thread t gets as a work package a function object of type <span style=\"font-family: courier new,courier;\">Sleeper<\/span>, the variable <span style=\"font-family: courier new,courier;\">valSleeper<\/span>, and the number 5 (line 27). The crucial observation is that the thread gets <span style=\"font-family: courier new,courier;\">valSleeper<\/span> by reference (line 9) and will be detached from the lifetime of the main thread (line 28). Then it will execute the call operator of the function object (lines 10 &#8211; 16). This method counts from 0 to 5, sleeps in each iteration 1\/10 of a second, and increments i by k. In the end, it displays its ID on the screen. Following Adam Riese (a German proverb), the result must be 1000 +&nbsp; 6 * 5 = 1030.<\/p>\n<p>But what happened? Something is going wrong.&nbsp;<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" class=\" size-full wp-image-4729\" src=\"https:\/\/www.modernescpp.com\/wp-content\/uploads\/2016\/04\/Sleeper.png\" alt=\"Sleeper\" style=\"margin: 15px;\" width=\"498\" height=\"175\" srcset=\"https:\/\/www.modernescpp.com\/wp-content\/uploads\/2016\/04\/Sleeper.png 498w, https:\/\/www.modernescpp.com\/wp-content\/uploads\/2016\/04\/Sleeper-300x105.png 300w\" sizes=\"auto, (max-width: 498px) 100vw, 498px\" \/><\/p>\n<p>There are two issues. On the one hand, <span style=\"font-family: courier new,courier;\">valSleeper<\/span> is 1000; on the other hand, the ID is missing on the console. So, that is undefined behavior. The reason is that the lifetime of the main thread ends before the child thread has performed its calculation or written its ID to <span style=\"font-family: courier new,courier;\">std::cout<\/span>.<\/p>\n<p>In case the main thread waits via<span style=\"font-family: courier new,courier;\"> t.join()<\/span> until this child thread is done with its work, we get the expected result.<\/p>\n<p>&nbsp;<\/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: #2b91af;\">int<\/span> main(){\r\n\r\n  std::cout &lt;&lt; std::endl;\r\n\r\n  <span style=\"color: #2b91af;\">int<\/span> valSleeper= 1000;\r\n  std::<span style=\"color: #0000ff;\">thread<\/span> t(Sleeper(valSleeper),5);\r\n  t.join();\r\n  std::cout &lt;&lt; <span style=\"color: #a31515;\">\"valSleeper = \"<\/span> &lt;&lt; valSleeper &lt;&lt; std::endl;\r\n\r\n  std::cout &lt;&lt; std::endl;\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-4730\" src=\"https:\/\/www.modernescpp.com\/wp-content\/uploads\/2016\/04\/Sleeper2.png\" alt=\"Sleeper2\" style=\"margin: 15px;\" width=\"561\" height=\"195\" srcset=\"https:\/\/www.modernescpp.com\/wp-content\/uploads\/2016\/04\/Sleeper2.png 561w, https:\/\/www.modernescpp.com\/wp-content\/uploads\/2016\/04\/Sleeper2-300x104.png 300w\" sizes=\"auto, (max-width: 561px) 100vw, 561px\" \/><\/p>\n<h2>What&#8217;s next?<\/h2>\n<p>Thinking about the lifetime of the threads is by far not the only issue with threads. Both threads, the main thread and the child thread, share two objects. That is <span style=\"font-family: courier new,courier;\">std::cout<\/span> and the variable <span style=\"font-family: courier new,courier;\">valSleeper.<\/span> Now, I described the classical recipe for a data race or &#8211; to say it differently &#8211; for undefined behavior. In the <a href=\"https:\/\/www.modernescpp.com\/index.php\/threads-sharing-data\">next post<\/a>, I will deal with shared variables between threads. (<strong>Proofreader Arne Mertz, <strong> Alexey Elymanov<\/strong><\/strong>)<\/p>\n<p>&nbsp;<\/p>\n<p>&nbsp;<\/p><\/p>\n","protected":false},"excerpt":{"rendered":"<p>A thread gets its data by copy or by reference. By default, you should use by copy. Why? In case your thread gets its data by reference, you have to be extremely careful about the lifetime of the arguments.<\/p>\n","protected":false},"author":21,"featured_media":4729,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[366],"tags":[],"class_list":["post-4731","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\/4731","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=4731"}],"version-history":[{"count":0,"href":"https:\/\/www.modernescpp.com\/index.php\/wp-json\/wp\/v2\/posts\/4731\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.modernescpp.com\/index.php\/wp-json\/wp\/v2\/media\/4729"}],"wp:attachment":[{"href":"https:\/\/www.modernescpp.com\/index.php\/wp-json\/wp\/v2\/media?parent=4731"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.modernescpp.com\/index.php\/wp-json\/wp\/v2\/categories?post=4731"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.modernescpp.com\/index.php\/wp-json\/wp\/v2\/tags?post=4731"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}