{"id":84634,"date":"2021-09-17T09:00:50","date_gmt":"2021-09-17T03:30:50","guid":{"rendered":"https:\/\/techvidvan.com\/tutorials\/?p=84634"},"modified":"2021-09-17T09:00:50","modified_gmt":"2021-09-17T03:30:50","slug":"cpp-multithreading","status":"publish","type":"post","link":"https:\/\/techvidvan.com\/tutorials\/cpp-multithreading\/","title":{"rendered":"Multithreading in C++ with Examples"},"content":{"rendered":"<p>The C++ programming language gives a ton of benefits to its users. It has various useful and efficient features and functionalities. In C++, Multithreading is one of the most important and useful features. Even today, Multithreading is one of the most used features. Let us learn more about it.<\/p>\n<h3>What is Multithreading in C++?<\/h3>\n<p>Multithreading is more like multitasking. With the help of multitasking, you can run two or more programs on your computer concurrently. There are two ways of multitasking such as process-based and thread-based.<\/p>\n<p>The process-based multitasking helps in maintaining the concurrent execution of programs. And thread-based multitasking helps in handling the concurrent execution of pieces of the same program.<\/p>\n<p>The meaning of multithreading is that two or more threads running concurrently. And each thread is handling a different task. It allows you to perform many activities simultaneously. C++ does not provide any support for Multithreaded applications, it entirely relies upon the operating system.<\/p>\n<p>Let\u2019s take an example to understand it better.<\/p>\n<p>When you login to your Facebook account or you go to the news feed then you can see live videos, you can comment or even like that video, everything occurs simultaneously.<\/p>\n<h3>What is a Thread?<\/h3>\n<p>A thread is a lightweight process. Each thread executes different parts of a program. And each thread shares memory and other system resources. All thread functions are declared in the &lt;pthread.h&gt; header file in linux.<\/p>\n<p>In this tutorial, we are going to use POSIX to write multithreaded C++ programs.<\/p>\n<p>POSIX threads provide API that are present on many UNIX-like operating systems such as OpenBSD, FreeBSD, GNU\/Linux, MAC OS X etc.<\/p>\n<h3>Creating Threads in C++<\/h3>\n<p>You can create a thread using the pthread_create() funcion.<br \/>\n<strong>Syntax:-<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">pthread_create(Idthread, attr, start_routine, arg)\n<\/pre>\n<p>In the above,<\/p>\n<ul>\n<li><strong>Idthread:<\/strong>&#8211; It is a unique identifier for each thread.<\/li>\n<li><strong>attr<\/strong>:- It is an attribute object that may be used to set multiple thread attributes. You can also provide thread attribute objects or you can set NULL for default values.<\/li>\n<li><strong>start_routine:-<\/strong> The thread will execute once it is created.<\/li>\n<li><strong>arg<\/strong>:- It is passed to start_routine as a single argument. It must be passed by reference as a pointer of type void. If you don\u2019t pass any argument then null is used.<\/li>\n<\/ul>\n<h3>Terminating Threads in C++<\/h3>\n<p>You can terminate any thread using the pthread_exit() function. Normally, the pthread_exit() routine is called after a thread has completed its work and it is not required to exist.<\/p>\n<p><strong>Example:- Creating threads in C++<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">#include &lt;iostream&gt;\n#include &lt;pthread.h&gt;\nusing namespace std;\n\nchar* st = \"Child thread\";\n\nvoid* fun(void *st)\n{\n  cout &lt;&lt; \"Created child thread: \" &lt;&lt; (char*)st;\n}\nint main()\n{\n  pthread_t t;    \n  pthread_create(&amp;t, NULL, &amp;fun, (void*)st);\n  cout &lt;&lt; \"Created Main thread!\" &lt;&lt; endl;\n  pthread_join(t, NULL);\n  exit(EXIT_SUCCESS);\n  return 0;\n}\n<\/pre>\n<p><strong>Output:-<\/strong><\/p>\n<div class=\"code-output\">Created Main thread!<br \/>\nCreated child thread: Child thread<\/div>\n<h3>Joining and Detaching threads in C++<\/h3>\n<p>You can also join or detach threads in C++.<\/p>\n<h4>join() function in C++<\/h4>\n<p>You have to use the join() function to join a thread. Main thread will terminate only after the termination of the child thread. Main thread waits for the child thread to complete execution.<\/p>\n<p><strong>Syntax:-<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">name_of_the_thread.join();\n<\/pre>\n<p>You can also check if a thread is joinable or not using the joinable() function. It returns bool value.<\/p>\n<p><strong>Syntax:-<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">name_of_the_thread.joinable();\n<\/pre>\n<h4>detach() function in C++<\/h4>\n<p>You can detach a thread from the parent thread using the detach() function. In this, the main and child thread execute independently.<\/p>\n<p><strong>Example:- Using C++ join() function<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">#include &lt;iostream&gt;\n#include &lt;unistd.h&gt;  \n#include &lt;pthread.h&gt;\nusing namespace std;\n\nstring str;\nvoid* fun(void*)\n{\n  sleep(1);   \n  cout &lt;&lt; \"Created child thread \" &lt;&lt; str &lt;&lt; endl;\n}\n\nint main()\n{\n  pthread_t t[4];\n  cout &lt;&lt; \"TechVidvan Tutorial: C++ Multithreading!\"&lt;&lt;endl&lt;&lt;endl;\n  for(int i=0; i&lt;4; i++)\n  {\n    \tcout &lt;&lt; \"Created -&gt; Thread T[\" &lt;&lt; i &lt;&lt; \"]!\" &lt;&lt; str &lt;&lt; endl;\n    \tpthread_create(&amp;t[i], NULL, &amp;fun, NULL);\n    \tpthread_join(t[i], NULL);\n}\nexit(EXIT_SUCCESS);\nreturn 0;\n}\n\n<\/pre>\n<p><strong>Output:-<\/strong><\/p>\n<div class=\"code-output\">\n<p>TechVidvan Tutorial: C++ Multithreading!<\/p>\n<p>Created -&gt; Thread T[0]!<br \/>\nCreated child thread<br \/>\nCreated -&gt; Thread T[1]!<br \/>\nCreated child thread<br \/>\nCreated -&gt; Thread T[2]!<br \/>\nCreated child thread<br \/>\nCreated -&gt; Thread T[3]!<br \/>\nCreated child thread<\/p>\n<\/div>\n<p><strong>Example:- Using C++ detach() function<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">#include &lt;iostream&gt;\n#include &lt;unistd.h&gt;   \n#include &lt;pthread.h&gt;\nusing namespace std;\n\nstring str;\nvoid* fun(void*)\n{\n  sleep(1);  \n  cout &lt;&lt; \"Created Child thread!\" &lt;&lt; str &lt;&lt; endl;\n}\n\nint main()\n{\n  pthread_t t[4];\n  for(int i=0; i&lt;4; i++)\n  {\n    \tcout &lt;&lt; \"Created -&gt; Thread T[\" &lt;&lt; i &lt;&lt; \"]!\" &lt;&lt; str &lt;&lt; endl;\n    \tpthread_create(&amp;t[i], NULL, &amp;fun, NULL);\n    \tpthread_detach(t[i]);\n}\nexit(EXIT_SUCCESS);\nreturn 0;\n}\n<\/pre>\n<p><strong>Output:-<\/strong><\/p>\n<div class=\"code-output\">Created -&gt; Thread T[0]!<br \/>\nCreated -&gt; Thread T[1]!<br \/>\nCreated -&gt; Thread T[2]!<br \/>\nCreated -&gt; Thread T[3]!<\/div>\n<h4>Passing arguments to threads in C++<\/h4>\n<p>You can pass multiple arguments to threads using a structure. You can pass any data type in a thread callback.<br \/>\n<strong>Example:-<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">#include &lt;iostream&gt;\n#include &lt;cstdlib&gt;\n#include &lt;pthread.h&gt;\n\nusing namespace std;\n\n#define NUM_THREADS 3\n\nstruct data{\n   int  thread_id;\n   char *msg;\n};\n\nvoid *DisplayHi(void *thread_arg) {\n   struct data *val;\n   val = (struct data *) thread_arg;\n\n   cout &lt;&lt; \"Thread ID : \" &lt;&lt; val-&gt;thread_id ;\n   cout &lt;&lt; \" Message : \" &lt;&lt; val-&gt;msg &lt;&lt; endl;\n\n   pthread_exit(NULL);\n}\n\nint main () {\n   pthread_t threads[NUM_THREADS];\n   struct data td[NUM_THREADS];\n   int rc;\n   int i;\n\n   for( i = 0; i &lt; NUM_THREADS; i++ ) {\n  \tcout &lt;&lt;\"Creating Thread: \" &lt;&lt; i &lt;&lt; endl;\n  \ttd[i].thread_id = i;\n  \ttd[i].msg = \"Just a friendly Message!\";\n  \trc = pthread_create(&amp;threads[i], NULL, DisplayHi, (void *)&amp;td[i]);\n \t \n  \tif (rc) {\n     \tcout &lt;&lt; \"Error:unable to create thread,\" &lt;&lt; rc &lt;&lt; endl;\n     \texit(0);\n  \t}\n   }\n   pthread_exit(NULL);\n} \n<\/pre>\n<p><strong>Output:-<\/strong><\/p>\n<div class=\"code-output\">Creating Thread: 0<br \/>\nCreating Thread: 1<br \/>\nThread ID : 0 Message : Just a friendly Message!<br \/>\nCreating Thread: 2<br \/>\nThread ID : 2 Message : Just a friendly Message!<br \/>\nThread ID : 1 Message : Just a friendly Message!<\/div>\n<h3>Advantages of Multithreading in C++<\/h3>\n<ul>\n<li>On a multi CPU system, Multithreading performs faster.<\/li>\n<li>Using this, you can reduce performance and concurrency.<\/li>\n<li>It helps you to access multiple applications simultaneously.<\/li>\n<li>It also helps in enabling a program to make best use of available CPU.<\/li>\n<\/ul>\n<h3>Summary<\/h3>\n<p>In this tutorial, we discussed what is thread and multithreading in C++\u00a0 We also discussed how you can create and terminate a thread. Then we talked over the process of joining and detaching threads in C++. We discussed how you can pass arguments to threads.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>The C++ programming language gives a ton of benefits to its users. It has various useful and efficient features and functionalities. In C++, Multithreading is one of the most important and useful features. Even&#46;&#46;&#46;<\/p>\n","protected":false},"author":1,"featured_media":84648,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[3405],"tags":[4287,4288,4289,4290],"class_list":["post-84634","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-cpp","tag-advantages-of-multithreading-in-c","tag-multithreading-in-c","tag-terminating-threads-in-c","tag-thread-in-c"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v27.7 - https:\/\/yoast.com\/product\/yoast-seo-wordpress\/ -->\n<title>Multithreading in C++ with Examples - TechVidvan<\/title>\n<meta name=\"description\" content=\"Learn what is thread &amp; multithreading in C++ with examples. Learn to create &amp; terminate C++ thread. See joining and detaching threads in C++.\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/techvidvan.com\/tutorials\/cpp-multithreading\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Multithreading in C++ with Examples - TechVidvan\" \/>\n<meta property=\"og:description\" content=\"Learn what is thread &amp; multithreading in C++ with examples. Learn to create &amp; terminate C++ thread. See joining and detaching threads in C++.\" \/>\n<meta property=\"og:url\" content=\"https:\/\/techvidvan.com\/tutorials\/cpp-multithreading\/\" \/>\n<meta property=\"og:site_name\" content=\"TechVidvan\" \/>\n<meta property=\"article:publisher\" content=\"https:\/\/www.facebook.com\/TechVidvan\/\" \/>\n<meta property=\"article:published_time\" content=\"2021-09-17T03:30:50+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2021\/08\/C-Multithreading.jpg\" \/>\n\t<meta property=\"og:image:width\" content=\"1200\" \/>\n\t<meta property=\"og:image:height\" content=\"628\" \/>\n\t<meta property=\"og:image:type\" content=\"image\/jpeg\" \/>\n<meta name=\"author\" content=\"TechVidvan Team\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:creator\" content=\"@vidvantech\" \/>\n<meta name=\"twitter:site\" content=\"@vidvantech\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"TechVidvan Team\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"5 minutes\" \/>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"Multithreading in C++ with Examples - TechVidvan","description":"Learn what is thread & multithreading in C++ with examples. Learn to create & terminate C++ thread. See joining and detaching threads in C++.","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/techvidvan.com\/tutorials\/cpp-multithreading\/","og_locale":"en_US","og_type":"article","og_title":"Multithreading in C++ with Examples - TechVidvan","og_description":"Learn what is thread & multithreading in C++ with examples. Learn to create & terminate C++ thread. See joining and detaching threads in C++.","og_url":"https:\/\/techvidvan.com\/tutorials\/cpp-multithreading\/","og_site_name":"TechVidvan","article_publisher":"https:\/\/www.facebook.com\/TechVidvan\/","article_published_time":"2021-09-17T03:30:50+00:00","og_image":[{"width":1200,"height":628,"url":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2021\/08\/C-Multithreading.jpg","type":"image\/jpeg"}],"author":"TechVidvan Team","twitter_card":"summary_large_image","twitter_creator":"@vidvantech","twitter_site":"@vidvantech","twitter_misc":{"Written by":"TechVidvan Team","Est. reading time":"5 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/techvidvan.com\/tutorials\/cpp-multithreading\/#article","isPartOf":{"@id":"https:\/\/techvidvan.com\/tutorials\/cpp-multithreading\/"},"author":{"name":"TechVidvan Team","@id":"https:\/\/techvidvan.com\/tutorials\/#\/schema\/person\/e9c26e74dd3d87421f7ada9433b8cd22"},"headline":"Multithreading in C++ with Examples","datePublished":"2021-09-17T03:30:50+00:00","mainEntityOfPage":{"@id":"https:\/\/techvidvan.com\/tutorials\/cpp-multithreading\/"},"wordCount":755,"commentCount":0,"publisher":{"@id":"https:\/\/techvidvan.com\/tutorials\/#organization"},"image":{"@id":"https:\/\/techvidvan.com\/tutorials\/cpp-multithreading\/#primaryimage"},"thumbnailUrl":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2021\/08\/C-Multithreading.jpg","keywords":["Advantages of Multithreading in C++","Multithreading in C++","Terminating Threads in C++","thread in C++"],"articleSection":["C++ Tutorials"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/techvidvan.com\/tutorials\/cpp-multithreading\/#respond"]}]},{"@type":"WebPage","@id":"https:\/\/techvidvan.com\/tutorials\/cpp-multithreading\/","url":"https:\/\/techvidvan.com\/tutorials\/cpp-multithreading\/","name":"Multithreading in C++ with Examples - TechVidvan","isPartOf":{"@id":"https:\/\/techvidvan.com\/tutorials\/#website"},"primaryImageOfPage":{"@id":"https:\/\/techvidvan.com\/tutorials\/cpp-multithreading\/#primaryimage"},"image":{"@id":"https:\/\/techvidvan.com\/tutorials\/cpp-multithreading\/#primaryimage"},"thumbnailUrl":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2021\/08\/C-Multithreading.jpg","datePublished":"2021-09-17T03:30:50+00:00","description":"Learn what is thread & multithreading in C++ with examples. Learn to create & terminate C++ thread. See joining and detaching threads in C++.","breadcrumb":{"@id":"https:\/\/techvidvan.com\/tutorials\/cpp-multithreading\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/techvidvan.com\/tutorials\/cpp-multithreading\/"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/techvidvan.com\/tutorials\/cpp-multithreading\/#primaryimage","url":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2021\/08\/C-Multithreading.jpg","contentUrl":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2021\/08\/C-Multithreading.jpg","width":1200,"height":628,"caption":"C++ Multithreading"},{"@type":"BreadcrumbList","@id":"https:\/\/techvidvan.com\/tutorials\/cpp-multithreading\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/techvidvan.com\/tutorials\/"},{"@type":"ListItem","position":2,"name":"Multithreading in C++ with Examples"}]},{"@type":"WebSite","@id":"https:\/\/techvidvan.com\/tutorials\/#website","url":"https:\/\/techvidvan.com\/tutorials\/","name":"TechVidvan Blogs","description":"","publisher":{"@id":"https:\/\/techvidvan.com\/tutorials\/#organization"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/techvidvan.com\/tutorials\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Organization","@id":"https:\/\/techvidvan.com\/tutorials\/#organization","name":"TechVidvan","url":"https:\/\/techvidvan.com\/tutorials\/","logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/techvidvan.com\/tutorials\/#\/schema\/logo\/image\/","url":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2024\/03\/techvidvan-logo-200x50-1.webp","contentUrl":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2024\/03\/techvidvan-logo-200x50-1.webp","width":200,"height":50,"caption":"TechVidvan"},"image":{"@id":"https:\/\/techvidvan.com\/tutorials\/#\/schema\/logo\/image\/"},"sameAs":["https:\/\/www.facebook.com\/TechVidvan\/","https:\/\/x.com\/vidvantech"]},{"@type":"Person","@id":"https:\/\/techvidvan.com\/tutorials\/#\/schema\/person\/e9c26e74dd3d87421f7ada9433b8cd22","name":"TechVidvan Team","description":"The TechVidvan Team delivers practical, beginner-friendly tutorials on programming, Java, Python, C++, DSA, AI, ML, data Science, Android, Flutter, MERN, Web Development, and technology. Our experts are here to help you upskill and excel in today\u2019s tech industry."}]}},"amp_enabled":true,"_links":{"self":[{"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/posts\/84634","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/comments?post=84634"}],"version-history":[{"count":0,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/posts\/84634\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/media\/84648"}],"wp:attachment":[{"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/media?parent=84634"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/categories?post=84634"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/tags?post=84634"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}