{"id":854,"date":"2023-03-10T16:43:46","date_gmt":"2023-03-10T09:43:46","guid":{"rendered":"https:\/\/csharptutorial.net\/?page_id=854"},"modified":"2023-03-10T19:19:31","modified_gmt":"2023-03-10T12:19:31","slug":"c-interlocked","status":"publish","type":"page","link":"https:\/\/www.csharptutorial.net\/csharp-concurrency\/c-interlocked\/","title":{"rendered":"C# Interlocked"},"content":{"rendered":"\n<p><strong>Summary<\/strong>: in this tutorial, you&#8217;ll learn how to use the C# <code>InterLocked<\/code> class to perform atomic operations on shared variables.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Introduction to the C# Interlocked class<\/h2>\n\n\n\n<p>The <code>Interlocked<\/code> class provides a set of methods that allow you to perform atomic operations on shared variables.<\/p>\n\n\n\n<p>For example, if multiple <a href=\"https:\/\/csharptutorial.net\/csharp-concurrency\/csharp-thread\/\">threads<\/a> modify a shared variable concurrently, the final value of the variable may be unpredictable or incorrect.<\/p>\n\n\n\n<p>The reason is that incrementing a variable is not an atomic operation because the program needs to perform three steps:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>First, read the current value of the shared variable.<\/li>\n\n\n\n<li>Second, increase the value.<\/li>\n\n\n\n<li>Third, write the new value back to the shared variable.<\/li>\n<\/ul>\n\n\n\n<p>If thread one is increasing the value but not yet writing the new value to the shared variable (at step 2), thread two may read the original value and increase it. As the result, the update from thread one may be lost.<\/p>\n\n\n\n<p>To solve this synchronization issue, you can use the <code>Increment()<\/code> method of the <code>Interlocked<\/code> class to increase the shared variable atomically. <\/p>\n\n\n\n<p>Unlike regular increments, the <code><code>Interlocked.Increament<\/code>()<\/code> method increments the shared variable atomically, ensuring that the operation is completed before another thread can access the variable. <\/p>\n\n\n\n<p>The following program demonstrates how to use the <code>InterLock<\/code> class to perform atomic increments of a shared variable <code>counter<\/code> across two threads: <\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-1\" data-shcb-language-name=\"C#\" data-shcb-language-slug=\"cs\"><span><code class=\"hljs language-cs\"><span class=\"hljs-keyword\">int<\/span> counter = <span class=\"hljs-number\">0<\/span>;\n\n<span class=\"hljs-function\"><span class=\"hljs-keyword\">void<\/span> <span class=\"hljs-title\">Increase<\/span>(<span class=\"hljs-params\"><\/span>)<\/span>\n{\n    <span class=\"hljs-keyword\">for<\/span> (<span class=\"hljs-keyword\">int<\/span> i = <span class=\"hljs-number\">0<\/span>; i &lt; <span class=\"hljs-number\">1000000<\/span>; i++)\n    {\n        Interlocked.Increment(<span class=\"hljs-keyword\">ref<\/span> counter);\n\n    }\n    Console.WriteLine(<span class=\"hljs-string\">\"The counter is \"<\/span> + counter);\n}\n\nTask.Run(() =&gt; Increase());\nTask.Run(() =&gt; Increase());\n\nConsole.ReadLine();<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-1\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">C#<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">cs<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>Output:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-2\" data-shcb-language-name=\"C#\" data-shcb-language-slug=\"cs\"><span><code class=\"hljs language-cs\">The counter <span class=\"hljs-keyword\">is<\/span> <span class=\"hljs-number\">1942623<\/span>\nThe counter <span class=\"hljs-keyword\">is<\/span> <span class=\"hljs-number\">2000000<\/span><\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-2\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">C#<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">cs<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p class=\"note\">If you wonder why the output has a random number like <code>1942623<\/code>, please check out the <code><a href=\"https:\/\/csharptutorial.net\/csharp-concurrency\/csharp-lock\/\">lock<\/a><\/code> tutorial for a detailed explanation.<\/p>\n\n\n\n<p>How it works.<\/p>\n\n\n\n<p>First, declare an integer variable <code>counter<\/code> and initialize its value to zero.<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-3\" data-shcb-language-name=\"C#\" data-shcb-language-slug=\"cs\"><span><code class=\"hljs language-cs\"><span class=\"hljs-keyword\">int<\/span> counter = <span class=\"hljs-number\">0<\/span>;<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-3\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">C#<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">cs<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>Second, define <code>Increase()<\/code> function that increments the <code>counter<\/code> using the <code>Increment()<\/code> method of the <code>Interlocked<\/code> class in a loop and displays the <code>counter<\/code> value to the console:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-4\" data-shcb-language-name=\"C#\" data-shcb-language-slug=\"cs\"><span><code class=\"hljs language-cs\"><span class=\"hljs-function\"><span class=\"hljs-keyword\">void<\/span> <span class=\"hljs-title\">Increase<\/span>(<span class=\"hljs-params\"><\/span>)<\/span>\n{\n    <span class=\"hljs-keyword\">for<\/span> (<span class=\"hljs-keyword\">int<\/span> i = <span class=\"hljs-number\">0<\/span>; i &lt; <span class=\"hljs-number\">1000000<\/span>; i++)\n    {\n        Interlocked.Increment(<span class=\"hljs-keyword\">ref<\/span> counter);\n\n    }\n    Console.WriteLine(<span class=\"hljs-string\">\"The counter is \"<\/span> + counter);\n}<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-4\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">C#<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">cs<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>Third, <a href=\"https:\/\/csharptutorial.net\/csharp-concurrency\/csharp-task\/\">create two tasks<\/a> that execute the <code>Increase()<\/code> method in separate threads. Both tasks (or threads) will increment the <code>counter<\/code> variable concurrently:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-5\" data-shcb-language-name=\"C#\" data-shcb-language-slug=\"cs\"><span><code class=\"hljs language-cs\">Task.Run(() =&gt; Increase());\nTask.Run(() =&gt; Increase());<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-5\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">C#<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">cs<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>Finally, use the <code><code>Console.ReadLine()<\/code><\/code> to pause the program and allow enough time for the two tasks to complete before you hit the enter (or return key):<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-6\" data-shcb-language-name=\"C#\" data-shcb-language-slug=\"cs\"><span><code class=\"hljs language-cs\">Console.ReadLine();<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-6\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">C#<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">cs<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<h2 class=\"wp-block-heading\">Interlocked vs. lock<\/h2>\n\n\n\n<p>Both <code>Interlocked<\/code> and <code>lock<\/code> allow thread synchronization and prevent race conditions when multiple threads attempt to access the same shared variable concurrently. But they have some differences:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><code>Interlocked<\/code> only provides atomic operations such as <code>Increment<\/code>, <code>Decrement<\/code>, <code>Exchange<\/code>, etc. These methods are useful when you need to perform on a shared variable.<\/li>\n\n\n\n<li>The <code>lock<\/code> statement provides mutual exclusion that allows only one thread can execute a critical block of code at a time.<\/li>\n<\/ul>\n\n\n\n<p>The <code>lock<\/code> can execute a block of code atomically while the <code>Interlocked<\/code> can perform limited operations on a shared variable atomically. In other words, the <code>Interlocked<\/code> is more lightweight than the <code>lock<\/code>.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Summary<\/h2>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Use the <code>Interlocked<\/code> class to perform atomic operations on shared variables.<\/li>\n<\/ul>\n<div class=\"helpful-block-content\" data-title=\"\">\n\t<header>\n\t\t<div class=\"wth-question\">Was this tutorial helpful ?<\/div>\n\t\t<div class=\"wth-thumbs\">\n\t\t\t<button\n\t\t\t\tdata-post=\"854\"\n\t\t\t\tdata-post-url=\"https:\/\/www.csharptutorial.net\/csharp-concurrency\/c-interlocked\/\"\n\t\t\t\tdata-post-title=\"C# Interlocked\"\n\t\t\t\tdata-response=\"1\"\n\t\t\t\tclass=\"wth-btn-rounded wth-yes-btn\"\n\t\t\t>\n\t\t\t\t<svg\n\t\t\t\t\txmlns=\"http:\/\/www.w3.org\/2000\/svg\"\n\t\t\t\t\tviewBox=\"0 0 24 24\"\n\t\t\t\t\tfill=\"none\"\n\t\t\t\t\tstroke=\"currentColor\"\n\t\t\t\t\tstroke-width=\"2\"\n\t\t\t\t\tstroke-linecap=\"round\"\n\t\t\t\t\tstroke-linejoin=\"round\"\n\t\t\t\t\tclass=\"feather feather-thumbs-up block w-full h-full\"\n\t\t\t\t>\n\t\t\t\t\t<path\n\t\t\t\t\t\td=\"M14 9V5a3 3 0 0 0-3-3l-4 9v11h11.28a2 2 0 0 0 2-1.7l1.38-9a2 2 0 0 0-2-2.3zM7 22H4a2 2 0 0 1-2-2v-7a2 2 0 0 1 2-2h3\"\n\t\t\t\t\t><\/path>\n\t\t\t\t<\/svg>\n\t\t\t\t<span class=\"sr-only\"> Yes <\/span>\n\t\t\t<\/button>\n\n\t\t\t<button\n\t\t\t\tdata-response=\"0\"\n\t\t\t\tdata-post=\"854\"\n\t\t\t\tdata-post-url=\"https:\/\/www.csharptutorial.net\/csharp-concurrency\/c-interlocked\/\"\n\t\t\t\tdata-post-title=\"C# Interlocked\"\n\t\t\t\tclass=\"wth-btn-rounded wth-no-btn\"\n\t\t\t>\n\t\t\t\t<svg\n\t\t\t\t\txmlns=\"http:\/\/www.w3.org\/2000\/svg\"\n\t\t\t\t\tviewBox=\"0 0 24 24\"\n\t\t\t\t\tfill=\"none\"\n\t\t\t\t\tstroke=\"currentColor\"\n\t\t\t\t\tstroke-width=\"2\"\n\t\t\t\t\tstroke-linecap=\"round\"\n\t\t\t\t\tstroke-linejoin=\"round\"\n\t\t\t\t>\n\t\t\t\t\t<path\n\t\t\t\t\t\td=\"M10 15v4a3 3 0 0 0 3 3l4-9V2H5.72a2 2 0 0 0-2 1.7l-1.38 9a2 2 0 0 0 2 2.3zm7-13h2.67A2.31 2.31 0 0 1 22 4v7a2.31 2.31 0 0 1-2.33 2H17\"\n\t\t\t\t\t><\/path>\n\t\t\t\t<\/svg>\n\t\t\t\t<span class=\"sr-only\"> No <\/span>\n\t\t\t<\/button>\n\t\t<\/div>\n\t<\/header>\n\n\t<div class=\"wth-form hidden\">\n\t\t<div class=\"wth-form-wrapper\">\n\t\t\t<div class=\"wth-title\"><\/div>\n\t\t\t\n\t\t\t<textarea class=\"wth-message\"><\/textarea>\n\n\t\t\t<button class=\"btn btn-primary wth-btn-submit\">Send<\/button>\n\t\t\t<button class=\"btn wth-btn-cancel\">Cancel<\/button>\n\t\t\n\t\t<\/div>\n\t<\/div>\n<\/div>\n","protected":false},"excerpt":{"rendered":"<p>Summary: in this tutorial, you&#8217;ll learn how to use the C# InterLocked class to perform atomic operations on shared variables. Introduction to the C# Interlocked class The Interlocked class provides a set of methods that allow you to perform atomic operations on shared variables. For example, if multiple threads modify a shared variable concurrently, the [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"parent":760,"menu_order":12,"comment_status":"closed","ping_status":"closed","template":"","meta":{"footnotes":""},"class_list":["post-854","page","type-page","status-publish","hentry"],"_links":{"self":[{"href":"https:\/\/www.csharptutorial.net\/wp-json\/wp\/v2\/pages\/854","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.csharptutorial.net\/wp-json\/wp\/v2\/pages"}],"about":[{"href":"https:\/\/www.csharptutorial.net\/wp-json\/wp\/v2\/types\/page"}],"author":[{"embeddable":true,"href":"https:\/\/www.csharptutorial.net\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.csharptutorial.net\/wp-json\/wp\/v2\/comments?post=854"}],"version-history":[{"count":2,"href":"https:\/\/www.csharptutorial.net\/wp-json\/wp\/v2\/pages\/854\/revisions"}],"predecessor-version":[{"id":870,"href":"https:\/\/www.csharptutorial.net\/wp-json\/wp\/v2\/pages\/854\/revisions\/870"}],"up":[{"embeddable":true,"href":"https:\/\/www.csharptutorial.net\/wp-json\/wp\/v2\/pages\/760"}],"wp:attachment":[{"href":"https:\/\/www.csharptutorial.net\/wp-json\/wp\/v2\/media?parent=854"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}