{"id":4727,"date":"2016-04-19T18:53:26","date_gmt":"2016-04-19T18:53:26","guid":{"rendered":"https:\/\/www.modernescpp.com\/index.php\/thread-creation\/"},"modified":"2023-06-26T12:59:07","modified_gmt":"2023-06-26T12:59:07","slug":"thread-creation","status":"publish","type":"post","link":"https:\/\/www.modernescpp.com\/index.php\/thread-creation\/","title":{"rendered":"Thread Creation"},"content":{"rendered":"<p>Thread creation is easy. Call &nbsp;<span style=\"font-family: courier new,courier;\">std::thread,<\/span> and a new thread will be created. The thread gets a work package and starts it immediately. The creator of the thread (the Parent) has to take care of the created thread (the child). The parent should wait until their child completes their task or has to detach himself from the child. The child thread can get its payload task arguments by copy or by reference.<\/p>\n<p><!--more--><\/p>\n<p>&nbsp;<\/p>\n<p>That was too fast. So the details will follow.<\/p>\n<\/p>\n<h2>Creation and execution of a thread<\/h2>\n<p>Now, a more formal approach: a thread gets a Callable and starts it immediately.<\/p>\n<p>This sentence needs a few notes.<\/p>\n<ul>\n<li>A Callable is an entity that behaves like a function. It can be a function, a function object, or a lambda function.<\/li>\n<li>A<a href=\"http:\/\/en.cppreference.com\/w\/cpp\/utility\/functional\"> function object<\/a> is an instance of a class for which the call operator is overloaded. The key difference between functions and function objects is that a function object can have a state.<\/li>\n<li>A <a href=\"http:\/\/en.cppreference.com\/w\/cpp\/language\/lambda\">lambda <\/a>(anonymous function) is a pure function body without a name. It can be invoked just in place. A lambda function can capture its calling context. That&#8217;s why they are often called closures.<\/li>\n<\/ul>\n<p>After the theory, a small example.<\/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\r\n34\r\n35\r\n36\r\n37\r\n38\r\n39<\/pre>\n<\/td>\n<td>\n<pre style=\"margin: 0; line-height: 125%;\"><span style=\"color: #008000;\">\/\/ createThread.cpp<\/span>\r\n\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;\">void<\/span> helloFunction(){\r\n  std::cout &lt;&lt; <span style=\"color: #a31515;\">\"Hello C++11 from function.\"<\/span> &lt;&lt; std::endl;\r\n}\r\n\r\n<span style=\"color: #0000ff;\">class<\/span> <span style=\"color: #2b91af;\">HelloFunctionObject<\/span>  {\r\n  public:\r\n    <span style=\"color: #2b91af;\">void<\/span> <span style=\"color: #0000ff;\">operator<\/span>()() <span style=\"color: #0000ff;\">const<\/span> {\r\n      std::cout &lt;&lt; <span style=\"color: #a31515;\">\"Hello C++11 from a function object.\"<\/span> &lt;&lt; std::endl;\r\n    }\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: #008000;\">\/\/ thread executing helloFunction<\/span>\r\n  std::<span style=\"color: #0000ff;\">thread<\/span> t1(helloFunction);\r\n\r\n  <span style=\"color: #008000;\">\/\/ thread executing helloFunctionObject<\/span>\r\n  HelloFunctionObject helloFunctionObject;\r\n  std::<span style=\"color: #0000ff;\">thread<\/span> t2(helloFunctionObject);\r\n\r\n  <span style=\"color: #008000;\">\/\/ thread executing lambda function<\/span>\r\n  std::<span style=\"color: #0000ff;\">thread<\/span> t3([]{std::cout &lt;&lt; <span style=\"color: #a31515;\">\"Hello C++11 from lambda function.\"<\/span> &lt;&lt; std::endl;});\r\n\r\n  <span style=\"color: #008000;\">\/\/ ensure that t1, t2 and t3 have finished before main terminates<\/span>\r\n  t1.join();\r\n  t2.join();\r\n  t3.join();\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>All threads &#8211; &nbsp;<span style=\"font-family: courier new,courier;\">t1, t2<\/span>, and <span style=\"font-family: courier new,courier;\">t3 &#8211;&nbsp;<\/span>write their messages to the console. The work package of thread <span style=\"font-family: courier new,courier;\"> <\/span> <span style=\"font-family: courier new,courier;\">t2 i<\/span>s a function object (lines 10 &#8211; 15), and the work package of thread <span style=\"font-family: courier new,courier;\">t3<\/span> is a lambda function (line 29). In lines 32 &#8211; 34, the Main thread or Parent waits until his children are done.<\/p>\n<p>Let&#8217;s have a look at the output. This is more interesting.<\/p>\n<p>&nbsp;<img loading=\"lazy\" decoding=\"async\" class=\" size-full wp-image-4726\" src=\"https:\/\/www.modernescpp.com\/wp-content\/uploads\/2016\/04\/createThread.png\" alt=\"createThread\" style=\"margin: 15px;\" width=\"538\" height=\"305\" srcset=\"https:\/\/www.modernescpp.com\/wp-content\/uploads\/2016\/04\/createThread.png 538w, https:\/\/www.modernescpp.com\/wp-content\/uploads\/2016\/04\/createThread-300x170.png 300w\" sizes=\"auto, (max-width: 538px) 100vw, 538px\" \/><\/p>\n<p>The two programs&#8217; execution results differ in two aspects. First, child threads will be executed in a different order. Second, the output is a little bit of a mess. So, in the second run, the line break of the function <span style=\"font-family: courier new,courier;\">helloFunction<\/span> happens after the lambda function call.<\/p>\n<h2>What&#8217;s next?<\/h2>\n<p>The <a href=\"https:\/\/www.modernescpp.com\/index.php\/threads-lifetime\">next article<\/a> will be about the lifetime of a thread. <strong>(Proofreader Alexey Elymanov)<\/strong><\/p>\n<p>&nbsp;<\/p>\n<p>&nbsp;<\/p>\n<p>&nbsp;<\/p>\n<p>&nbsp;<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Thread creation is easy. Call &nbsp;std::thread, and a new thread will be created. The thread gets a work package and starts it immediately. The creator of the thread (the Parent) has to take care of the created thread (the child). The parent should wait until their child completes their task or has to detach himself [&hellip;]<\/p>\n","protected":false},"author":21,"featured_media":4726,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[366],"tags":[],"class_list":["post-4727","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\/4727","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=4727"}],"version-history":[{"count":1,"href":"https:\/\/www.modernescpp.com\/index.php\/wp-json\/wp\/v2\/posts\/4727\/revisions"}],"predecessor-version":[{"id":6985,"href":"https:\/\/www.modernescpp.com\/index.php\/wp-json\/wp\/v2\/posts\/4727\/revisions\/6985"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.modernescpp.com\/index.php\/wp-json\/wp\/v2\/media\/4726"}],"wp:attachment":[{"href":"https:\/\/www.modernescpp.com\/index.php\/wp-json\/wp\/v2\/media?parent=4727"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.modernescpp.com\/index.php\/wp-json\/wp\/v2\/categories?post=4727"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.modernescpp.com\/index.php\/wp-json\/wp\/v2\/tags?post=4727"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}