{"id":27033,"date":"2024-03-16T07:45:29","date_gmt":"2024-03-16T07:45:29","guid":{"rendered":"https:\/\/www.silicloud.com\/blog\/how-to-implement-data-sharing-among-multiple-threads-in-c\/"},"modified":"2024-03-22T10:02:32","modified_gmt":"2024-03-22T10:02:32","slug":"how-to-implement-data-sharing-among-multiple-threads-in-c","status":"publish","type":"post","link":"https:\/\/www.silicloud.com\/blog\/how-to-implement-data-sharing-among-multiple-threads-in-c\/","title":{"rendered":"How to implement data sharing among multiple threads in C++?"},"content":{"rendered":"<p>In C++, shared data in multi-threading can be implemented using mutexes and condition variables.<\/p>\n<p>Mutex locks are used to protect shared data, ensuring that only one thread can access the shared data at any given time. When a thread needs to access shared data, it must first acquire the mutex lock, and then release the mutex lock after accessing the shared data to allow other threads to continue accessing.<\/p>\n<p>Condition variables are used for synchronization and communication between threads. One thread can wait for a condition to be met by waiting on a condition variable, while another thread can notify the waiting thread that the condition has been met by signaling. Condition variables are typically used in conjunction with mutex locks to ensure that there is no race condition while waiting for the condition to be met.<\/p>\n<p>The following is an example code demonstrating how to use mutex locks and condition variables to implement multiple threads sharing data.<\/p>\n<pre class=\"post-pre\"><code><span class=\"hljs-meta\">#<span class=\"hljs-keyword\">include<\/span> <span class=\"hljs-string\">&lt;iostream&gt;<\/span><\/span>\r\n<span class=\"hljs-meta\">#<span class=\"hljs-keyword\">include<\/span> <span class=\"hljs-string\">&lt;thread&gt;<\/span><\/span>\r\n<span class=\"hljs-meta\">#<span class=\"hljs-keyword\">include<\/span> <span class=\"hljs-string\">&lt;mutex&gt;<\/span><\/span>\r\n<span class=\"hljs-meta\">#<span class=\"hljs-keyword\">include<\/span> <span class=\"hljs-string\">&lt;condition_variable&gt;<\/span><\/span>\r\n\r\nstd::mutex mtx;  <span class=\"hljs-comment\">\/\/ \u4e92\u65a5\u9501<\/span>\r\nstd::condition_variable cv;  <span class=\"hljs-comment\">\/\/ \u6761\u4ef6\u53d8\u91cf<\/span>\r\n<span class=\"hljs-type\">int<\/span> sharedData = <span class=\"hljs-number\">0<\/span>;  <span class=\"hljs-comment\">\/\/ \u5171\u4eab\u6570\u636e<\/span>\r\n\r\n<span class=\"hljs-function\"><span class=\"hljs-type\">void<\/span> <span class=\"hljs-title\">worker<\/span><span class=\"hljs-params\">(<span class=\"hljs-type\">int<\/span> id)<\/span> <\/span>{\r\n  <span class=\"hljs-function\">std::unique_lock&lt;std::mutex&gt; <span class=\"hljs-title\">lock<\/span><span class=\"hljs-params\">(mtx)<\/span><\/span>;  <span class=\"hljs-comment\">\/\/ \u83b7\u53d6\u4e92\u65a5\u9501<\/span>\r\n\r\n  <span class=\"hljs-comment\">\/\/ \u7b49\u5f85\u5171\u4eab\u6570\u636e\u88ab\u66f4\u65b0\u4e3a\u6307\u5b9a\u503c<\/span>\r\n  cv.<span class=\"hljs-built_in\">wait<\/span>(lock, []{ <span class=\"hljs-keyword\">return<\/span> sharedData == <span class=\"hljs-number\">42<\/span>; });\r\n\r\n  <span class=\"hljs-comment\">\/\/ \u8bbf\u95ee\u5171\u4eab\u6570\u636e<\/span>\r\n  std::cout &lt;&lt; <span class=\"hljs-string\">\"Thread \"<\/span> &lt;&lt; id &lt;&lt; <span class=\"hljs-string\">\": Shared data = \"<\/span> &lt;&lt; sharedData &lt;&lt; std::endl;\r\n\r\n  <span class=\"hljs-comment\">\/\/ \u91ca\u653e\u4e92\u65a5\u9501<\/span>\r\n  lock.<span class=\"hljs-built_in\">unlock<\/span>();\r\n}\r\n\r\n<span class=\"hljs-function\"><span class=\"hljs-type\">int<\/span> <span class=\"hljs-title\">main<\/span><span class=\"hljs-params\">()<\/span> <\/span>{\r\n  <span class=\"hljs-function\">std::thread <span class=\"hljs-title\">t1<\/span><span class=\"hljs-params\">(worker, <span class=\"hljs-number\">1<\/span>)<\/span><\/span>;\r\n  <span class=\"hljs-function\">std::thread <span class=\"hljs-title\">t2<\/span><span class=\"hljs-params\">(worker, <span class=\"hljs-number\">2<\/span>)<\/span><\/span>;\r\n\r\n  <span class=\"hljs-comment\">\/\/ \u66f4\u65b0\u5171\u4eab\u6570\u636e<\/span>\r\n  std::this_thread::<span class=\"hljs-built_in\">sleep_for<\/span>(std::chrono::<span class=\"hljs-built_in\">seconds<\/span>(<span class=\"hljs-number\">2<\/span>));  <span class=\"hljs-comment\">\/\/ \u6a21\u62df\u4e00\u6bb5\u8017\u65f6\u64cd\u4f5c<\/span>\r\n  {\r\n    <span class=\"hljs-function\">std::lock_guard&lt;std::mutex&gt; <span class=\"hljs-title\">lock<\/span><span class=\"hljs-params\">(mtx)<\/span><\/span>;  <span class=\"hljs-comment\">\/\/ \u83b7\u53d6\u4e92\u65a5\u9501<\/span>\r\n\r\n    sharedData = <span class=\"hljs-number\">42<\/span>;\r\n\r\n    <span class=\"hljs-comment\">\/\/ \u901a\u77e5\u7b49\u5f85\u7684\u7ebf\u7a0b\u6761\u4ef6\u5df2\u7ecf\u6210\u7acb<\/span>\r\n    cv.<span class=\"hljs-built_in\">notify_all<\/span>();\r\n  }\r\n\r\n  t1.<span class=\"hljs-built_in\">join<\/span>();\r\n  t2.<span class=\"hljs-built_in\">join<\/span>();\r\n\r\n  <span class=\"hljs-keyword\">return<\/span> <span class=\"hljs-number\">0<\/span>;\r\n}\r\n<\/code><\/pre>\n<p>In this example, two threads (t1 and t2) are waiting for the shared data to be updated to a specified value (42). The main thread updates the shared data after a period of waiting, and signals to the waiting threads that the condition has been met. Once awakened, the waiting threads will acquire the mutex lock again and access the shared data.<\/p>\n<p>It is important to note that the use of mutex locks and condition variables must be paired, meaning the same mutex lock should be used when waiting for a condition. Additionally, when using mutex locks and condition variables, one should avoid the occurrence of deadlocks and race conditions by carefully designing and adjusting the execution order and operations of threads.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>In C++, shared data in multi-threading can be implemented using mutexes and condition variables. Mutex locks are used to protect shared data, ensuring that only one thread can access the shared data at any given time. When a thread needs to access shared data, it must first acquire the mutex lock, and then release the [&hellip;]<\/p>\n","protected":false},"author":10,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_import_markdown_pro_load_document_selector":0,"_import_markdown_pro_submit_text_textarea":"","footnotes":""},"categories":[1],"tags":[],"class_list":["post-27033","post","type-post","status-publish","format-standard","hentry","category-uncategorized"],"yoast_head":"<!-- This site is optimized with the Yoast SEO Premium plugin v21.5 (Yoast SEO v21.5) - https:\/\/yoast.com\/wordpress\/plugins\/seo\/ -->\n<title>How to implement data sharing among multiple threads in C++? - Blog - Silicon Cloud<\/title>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/www.silicloud.com\/blog\/how-to-implement-data-sharing-among-multiple-threads-in-c\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"How to implement data sharing among multiple threads in C++?\" \/>\n<meta property=\"og:description\" content=\"In C++, shared data in multi-threading can be implemented using mutexes and condition variables. Mutex locks are used to protect shared data, ensuring that only one thread can access the shared data at any given time. When a thread needs to access shared data, it must first acquire the mutex lock, and then release the [&hellip;]\" \/>\n<meta property=\"og:url\" content=\"https:\/\/www.silicloud.com\/blog\/how-to-implement-data-sharing-among-multiple-threads-in-c\/\" \/>\n<meta property=\"og:site_name\" content=\"Blog - Silicon Cloud\" \/>\n<meta property=\"article:publisher\" content=\"https:\/\/www.facebook.com\/SiliCloudGlobal\/\" \/>\n<meta property=\"article:published_time\" content=\"2024-03-16T07:45:29+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2024-03-22T10:02:32+00:00\" \/>\n<meta name=\"author\" content=\"Jackson Davis\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:creator\" content=\"@SiliCloudGlobal\" \/>\n<meta name=\"twitter:site\" content=\"@SiliCloudGlobal\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"Jackson Davis\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"2 minutes\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\/\/schema.org\",\"@graph\":[{\"@type\":\"Article\",\"@id\":\"https:\/\/www.silicloud.com\/blog\/how-to-implement-data-sharing-among-multiple-threads-in-c\/#article\",\"isPartOf\":{\"@id\":\"https:\/\/www.silicloud.com\/blog\/how-to-implement-data-sharing-among-multiple-threads-in-c\/\"},\"author\":{\"name\":\"Jackson Davis\",\"@id\":\"https:\/\/www.silicloud.com\/blog\/#\/schema\/person\/55a10b8b0457c35884c25677889ad350\"},\"headline\":\"How to implement data sharing among multiple threads in C++?\",\"datePublished\":\"2024-03-16T07:45:29+00:00\",\"dateModified\":\"2024-03-22T10:02:32+00:00\",\"mainEntityOfPage\":{\"@id\":\"https:\/\/www.silicloud.com\/blog\/how-to-implement-data-sharing-among-multiple-threads-in-c\/\"},\"wordCount\":289,\"commentCount\":0,\"publisher\":{\"@id\":\"https:\/\/www.silicloud.com\/blog\/#organization\"},\"inLanguage\":\"en-US\"},{\"@type\":\"WebPage\",\"@id\":\"https:\/\/www.silicloud.com\/blog\/how-to-implement-data-sharing-among-multiple-threads-in-c\/\",\"url\":\"https:\/\/www.silicloud.com\/blog\/how-to-implement-data-sharing-among-multiple-threads-in-c\/\",\"name\":\"How to implement data sharing among multiple threads in C++? - Blog - Silicon Cloud\",\"isPartOf\":{\"@id\":\"https:\/\/www.silicloud.com\/blog\/#website\"},\"datePublished\":\"2024-03-16T07:45:29+00:00\",\"dateModified\":\"2024-03-22T10:02:32+00:00\",\"breadcrumb\":{\"@id\":\"https:\/\/www.silicloud.com\/blog\/how-to-implement-data-sharing-among-multiple-threads-in-c\/#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\/\/www.silicloud.com\/blog\/how-to-implement-data-sharing-among-multiple-threads-in-c\/\"]}]},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\/\/www.silicloud.com\/blog\/how-to-implement-data-sharing-among-multiple-threads-in-c\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"https:\/\/www.silicloud.com\/blog\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"How to implement data sharing among multiple threads in C++?\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\/\/www.silicloud.com\/blog\/#website\",\"url\":\"https:\/\/www.silicloud.com\/blog\/\",\"name\":\"Silicon Cloud Blog\",\"description\":\"\",\"publisher\":{\"@id\":\"https:\/\/www.silicloud.com\/blog\/#organization\"},\"inLanguage\":\"en-US\"},{\"@type\":\"Organization\",\"@id\":\"https:\/\/www.silicloud.com\/blog\/#organization\",\"name\":\"Silicon Cloud Blog\",\"url\":\"https:\/\/www.silicloud.com\/blog\/\",\"logo\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/www.silicloud.com\/blog\/#\/schema\/logo\/image\/\",\"url\":\"https:\/\/www.silicloud.com\/blog\/wp-content\/uploads\/2023\/11\/EN-SILICON-Full.png\",\"contentUrl\":\"https:\/\/www.silicloud.com\/blog\/wp-content\/uploads\/2023\/11\/EN-SILICON-Full.png\",\"width\":1024,\"height\":1024,\"caption\":\"Silicon Cloud Blog\"},\"image\":{\"@id\":\"https:\/\/www.silicloud.com\/blog\/#\/schema\/logo\/image\/\"},\"sameAs\":[\"https:\/\/www.facebook.com\/SiliCloudGlobal\/\",\"https:\/\/twitter.com\/SiliCloudGlobal\"]},{\"@type\":\"Person\",\"@id\":\"https:\/\/www.silicloud.com\/blog\/#\/schema\/person\/55a10b8b0457c35884c25677889ad350\",\"name\":\"Jackson Davis\",\"image\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/www.silicloud.com\/blog\/#\/schema\/person\/image\/\",\"url\":\"https:\/\/secure.gravatar.com\/avatar\/2fdb47d6df1226e92380d96973782572a97b0675d098bb914410dec348eb5d29?s=96&d=mm&r=g\",\"contentUrl\":\"https:\/\/secure.gravatar.com\/avatar\/2fdb47d6df1226e92380d96973782572a97b0675d098bb914410dec348eb5d29?s=96&d=mm&r=g\",\"caption\":\"Jackson Davis\"},\"url\":\"https:\/\/www.silicloud.com\/blog\/author\/jacksondavis\/\"}]}<\/script>\n<!-- \/ Yoast SEO Premium plugin. -->","yoast_head_json":{"title":"How to implement data sharing among multiple threads in C++? - Blog - Silicon Cloud","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:\/\/www.silicloud.com\/blog\/how-to-implement-data-sharing-among-multiple-threads-in-c\/","og_locale":"en_US","og_type":"article","og_title":"How to implement data sharing among multiple threads in C++?","og_description":"In C++, shared data in multi-threading can be implemented using mutexes and condition variables. Mutex locks are used to protect shared data, ensuring that only one thread can access the shared data at any given time. When a thread needs to access shared data, it must first acquire the mutex lock, and then release the [&hellip;]","og_url":"https:\/\/www.silicloud.com\/blog\/how-to-implement-data-sharing-among-multiple-threads-in-c\/","og_site_name":"Blog - Silicon Cloud","article_publisher":"https:\/\/www.facebook.com\/SiliCloudGlobal\/","article_published_time":"2024-03-16T07:45:29+00:00","article_modified_time":"2024-03-22T10:02:32+00:00","author":"Jackson Davis","twitter_card":"summary_large_image","twitter_creator":"@SiliCloudGlobal","twitter_site":"@SiliCloudGlobal","twitter_misc":{"Written by":"Jackson Davis","Est. reading time":"2 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/www.silicloud.com\/blog\/how-to-implement-data-sharing-among-multiple-threads-in-c\/#article","isPartOf":{"@id":"https:\/\/www.silicloud.com\/blog\/how-to-implement-data-sharing-among-multiple-threads-in-c\/"},"author":{"name":"Jackson Davis","@id":"https:\/\/www.silicloud.com\/blog\/#\/schema\/person\/55a10b8b0457c35884c25677889ad350"},"headline":"How to implement data sharing among multiple threads in C++?","datePublished":"2024-03-16T07:45:29+00:00","dateModified":"2024-03-22T10:02:32+00:00","mainEntityOfPage":{"@id":"https:\/\/www.silicloud.com\/blog\/how-to-implement-data-sharing-among-multiple-threads-in-c\/"},"wordCount":289,"commentCount":0,"publisher":{"@id":"https:\/\/www.silicloud.com\/blog\/#organization"},"inLanguage":"en-US"},{"@type":"WebPage","@id":"https:\/\/www.silicloud.com\/blog\/how-to-implement-data-sharing-among-multiple-threads-in-c\/","url":"https:\/\/www.silicloud.com\/blog\/how-to-implement-data-sharing-among-multiple-threads-in-c\/","name":"How to implement data sharing among multiple threads in C++? - Blog - Silicon Cloud","isPartOf":{"@id":"https:\/\/www.silicloud.com\/blog\/#website"},"datePublished":"2024-03-16T07:45:29+00:00","dateModified":"2024-03-22T10:02:32+00:00","breadcrumb":{"@id":"https:\/\/www.silicloud.com\/blog\/how-to-implement-data-sharing-among-multiple-threads-in-c\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/www.silicloud.com\/blog\/how-to-implement-data-sharing-among-multiple-threads-in-c\/"]}]},{"@type":"BreadcrumbList","@id":"https:\/\/www.silicloud.com\/blog\/how-to-implement-data-sharing-among-multiple-threads-in-c\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/www.silicloud.com\/blog\/"},{"@type":"ListItem","position":2,"name":"How to implement data sharing among multiple threads in C++?"}]},{"@type":"WebSite","@id":"https:\/\/www.silicloud.com\/blog\/#website","url":"https:\/\/www.silicloud.com\/blog\/","name":"Silicon Cloud Blog","description":"","publisher":{"@id":"https:\/\/www.silicloud.com\/blog\/#organization"},"inLanguage":"en-US"},{"@type":"Organization","@id":"https:\/\/www.silicloud.com\/blog\/#organization","name":"Silicon Cloud Blog","url":"https:\/\/www.silicloud.com\/blog\/","logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/www.silicloud.com\/blog\/#\/schema\/logo\/image\/","url":"https:\/\/www.silicloud.com\/blog\/wp-content\/uploads\/2023\/11\/EN-SILICON-Full.png","contentUrl":"https:\/\/www.silicloud.com\/blog\/wp-content\/uploads\/2023\/11\/EN-SILICON-Full.png","width":1024,"height":1024,"caption":"Silicon Cloud Blog"},"image":{"@id":"https:\/\/www.silicloud.com\/blog\/#\/schema\/logo\/image\/"},"sameAs":["https:\/\/www.facebook.com\/SiliCloudGlobal\/","https:\/\/twitter.com\/SiliCloudGlobal"]},{"@type":"Person","@id":"https:\/\/www.silicloud.com\/blog\/#\/schema\/person\/55a10b8b0457c35884c25677889ad350","name":"Jackson Davis","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/www.silicloud.com\/blog\/#\/schema\/person\/image\/","url":"https:\/\/secure.gravatar.com\/avatar\/2fdb47d6df1226e92380d96973782572a97b0675d098bb914410dec348eb5d29?s=96&d=mm&r=g","contentUrl":"https:\/\/secure.gravatar.com\/avatar\/2fdb47d6df1226e92380d96973782572a97b0675d098bb914410dec348eb5d29?s=96&d=mm&r=g","caption":"Jackson Davis"},"url":"https:\/\/www.silicloud.com\/blog\/author\/jacksondavis\/"}]}},"_links":{"self":[{"href":"https:\/\/www.silicloud.com\/blog\/wp-json\/wp\/v2\/posts\/27033","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.silicloud.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.silicloud.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.silicloud.com\/blog\/wp-json\/wp\/v2\/users\/10"}],"replies":[{"embeddable":true,"href":"https:\/\/www.silicloud.com\/blog\/wp-json\/wp\/v2\/comments?post=27033"}],"version-history":[{"count":1,"href":"https:\/\/www.silicloud.com\/blog\/wp-json\/wp\/v2\/posts\/27033\/revisions"}],"predecessor-version":[{"id":61238,"href":"https:\/\/www.silicloud.com\/blog\/wp-json\/wp\/v2\/posts\/27033\/revisions\/61238"}],"wp:attachment":[{"href":"https:\/\/www.silicloud.com\/blog\/wp-json\/wp\/v2\/media?parent=27033"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.silicloud.com\/blog\/wp-json\/wp\/v2\/categories?post=27033"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.silicloud.com\/blog\/wp-json\/wp\/v2\/tags?post=27033"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}