{"id":733,"date":"2023-10-07T17:29:36","date_gmt":"2023-10-07T17:29:36","guid":{"rendered":"https:\/\/baldsolutions.com\/?p=733"},"modified":"2023-10-28T08:45:38","modified_gmt":"2023-10-28T08:45:38","slug":"1-synchronization-primitives-in-net-interlocked-class","status":"publish","type":"post","link":"https:\/\/baldsolutions.com\/index.php\/2023\/10\/07\/1-synchronization-primitives-in-net-interlocked-class\/","title":{"rendered":"#1 Synchronization primitives in .NET &#8211; Interlocked class"},"content":{"rendered":"\n<p><\/p>\n\n\n\n<h1 class=\"wp-block-heading\">Introduction<\/h1>\n\n\n\n<p>To coordinate threads interaction when accessing a shared resource some kind of synchronization mechanism is required.  .NET offers many synchronization primitives that user can utilise according to a particular need. <\/p>\n\n\n\n<p>In this post I present one of the synchronization primitives &#8211; Interlocked class.<\/p>\n\n\n\n<p>This is a first post of the synchronization primitives series. I plan to add more posts to describe other primitives that .NET offers (e.g. Mutex, SemaphoreSlim, Barrier etc.).<\/p>\n\n\n\n<h1 class=\"wp-block-heading\">Interlocked class<\/h1>\n\n\n\n<p>The <a href=\"https:\/\/learn.microsoft.com\/en-us\/dotnet\/api\/system.threading.interlocked?view=net-7.0\" target=\"_blank\" rel=\"noopener\" title=\"\">Interlocked <\/a>class is a static class that provides atomic operations for variables that are shared by multiple threads (as per <a href=\"https:\/\/learn.microsoft.com\/en-us\/dotnet\/api\/system.threading.interlocked?view=net-7.0\" target=\"_blank\" rel=\"noopener\" title=\"\">docs<\/a>). Let&#8217;s focus on a simple incrementation operation and the following example:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>we have a global variable named <code>counter<\/code>,<\/li>\n\n\n\n<li>we run many threads at the same time that increment the <code>counter<\/code> value.<\/li>\n<\/ul>\n\n\n\n<p>At first everything looks fine as incrementing the <code>counter<\/code> looks like something that cannot be messed up in terms of accessing by many threads &#8211; but it is not true. As you can read in the <a href=\"https:\/\/learn.microsoft.com\/en-us\/dotnet\/api\/system.threading.interlocked?view=net-7.0#remarks\" target=\"_blank\" rel=\"noopener\" title=\"\">docs<\/a> &#8211; on most computers incrementing is not an atomic operation and consists of three steps:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>load a <code>counter<\/code> value into a register,<\/li>\n\n\n\n<li>increment the value,<\/li>\n\n\n\n<li>store a value in the <code>counter<\/code>  variable. <\/li>\n<\/ul>\n\n\n\n<p>As you can see instead of one (apparently) one atomic operation there are tree steps that happen behind the scene. Thread can be preempted after executing the first two steps, then another thread executes all three steps and at the end first thread finishes the last step. In this case instead of having the <code>counter + 2<\/code> result the result is <code>counter + 1<\/code>:<\/p>\n\n\n\n<figure class=\"wp-block-image size-full\"><img loading=\"lazy\" decoding=\"async\" width=\"680\" height=\"315\" src=\"https:\/\/baldsolutions.com\/wp-content\/uploads\/2023\/10\/image-6.png\" alt=\"\" class=\"wp-image-750\" srcset=\"https:\/\/baldsolutions.com\/wp-content\/uploads\/2023\/10\/image-6.png 680w, https:\/\/baldsolutions.com\/wp-content\/uploads\/2023\/10\/image-6-300x139.png 300w\" sizes=\"auto, (max-width: 680px) 100vw, 680px\" \/><\/figure>\n\n\n\n<h1 class=\"wp-block-heading\">Example<\/h1>\n\n\n\n<p>Let&#8217;s consider the source code from my <a href=\"https:\/\/github.com\/tglowka\/baldsolutions\/blob\/master\/dotnet\/synchronization-primitives\/Program.cs\" target=\"_blank\" rel=\"noopener\" title=\"\">GitHub<\/a>. As you can see the <code>StandardIncrement<\/code> method increments passed argument using <code>++<\/code> operator whereas the <code>InterlockedIncrement<\/code> method uses the <code>Interlocked.Increment<\/code>. If you run the provided code using <code>dotnet run -c Release<\/code> command you might see a similar output:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>StandardIncrement: 9985\nInterlockedIncrement: 10000<\/code><\/pre>\n\n\n\n<h1 class=\"wp-block-heading\">Behind the scene<\/h1>\n\n\n\n<p>Let&#8217;s see what are the ASM instructions for the source code. For this purpose we will use <a href=\"https:\/\/sharplab.io\/\" target=\"_blank\" rel=\"noopener\" title=\"\">sharplab<\/a> &#8211; interesting part of the output is highlighted:<\/p>\n\n\n\n<figure class=\"wp-block-image size-full\"><img loading=\"lazy\" decoding=\"async\" width=\"954\" height=\"653\" src=\"https:\/\/baldsolutions.com\/wp-content\/uploads\/2023\/10\/image-9.png\" alt=\"\" class=\"wp-image-753\" srcset=\"https:\/\/baldsolutions.com\/wp-content\/uploads\/2023\/10\/image-9.png 954w, https:\/\/baldsolutions.com\/wp-content\/uploads\/2023\/10\/image-9-300x205.png 300w, https:\/\/baldsolutions.com\/wp-content\/uploads\/2023\/10\/image-9-768x526.png 768w\" sizes=\"auto, (max-width: 954px) 100vw, 954px\" \/><\/figure>\n\n\n\n<p>What we can see is that these two methods (while doing the same) are represented by  slightly different instructions. The <code>InterlockedIncrement <\/code>method uses the LOCK prefix which makes the instruction atomic whereas the <code>StandardIncrement<\/code> does not (interesting explanation in the <a href=\"https:\/\/stackoverflow.com\/questions\/10109679\/how-come-inc-instruction-of-x86-is-not-atomic\" target=\"_blank\" rel=\"noopener\" title=\"\">link<\/a>).<\/p>\n\n\n\n<h1 class=\"wp-block-heading\">Summary<\/h1>\n\n\n\n<p>In this post I presented and explained the <code>Interlocked<\/code> synchronization primitive in the .NET environment.  The <a href=\"https:\/\/learn.microsoft.com\/en-us\/dotnet\/api\/system.threading.interlocked?view=net-7.0#methods\" target=\"_blank\" rel=\"noopener\" title=\"\">API <\/a> of the<code>Interlocked<\/code> class consists of many methods and I encourage you to give it a try on your own. As always you can find source code on my <a href=\"https:\/\/github.com\/tglowka\/baldsolutions\/tree\/master\/dotnet\/synchronization-primitives\" target=\"_blank\" rel=\"noopener\" title=\"\">GitHub <\/a>repository.<\/p>\n\n\n\n<p>Have a nice day, bye!<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Introduction To coordinate threads interaction when accessing a shared resource some kind of synchronization mechanism is required. .NET offers many synchronization primitives that user can&#8230;<\/p>\n<div class=\"more-link-wrapper\"><a class=\"more-link\" href=\"https:\/\/baldsolutions.com\/index.php\/2023\/10\/07\/1-synchronization-primitives-in-net-interlocked-class\/\">Continue reading<span class=\"screen-reader-text\">#1 Synchronization primitives in .NET &#8211; Interlocked class<\/span><\/a><\/div>\n","protected":false},"author":3,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_monsterinsights_skip_tracking":false,"_monsterinsights_sitenote_active":false,"_monsterinsights_sitenote_note":"","_monsterinsights_sitenote_category":0,"footnotes":""},"categories":[2,16],"tags":[],"class_list":["post-733","post","type-post","status-publish","format-standard","hentry","category-net","category-synchronization-primitives","entry"],"aioseo_notices":[],"_links":{"self":[{"href":"https:\/\/baldsolutions.com\/index.php\/wp-json\/wp\/v2\/posts\/733","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/baldsolutions.com\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/baldsolutions.com\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/baldsolutions.com\/index.php\/wp-json\/wp\/v2\/users\/3"}],"replies":[{"embeddable":true,"href":"https:\/\/baldsolutions.com\/index.php\/wp-json\/wp\/v2\/comments?post=733"}],"version-history":[{"count":13,"href":"https:\/\/baldsolutions.com\/index.php\/wp-json\/wp\/v2\/posts\/733\/revisions"}],"predecessor-version":[{"id":780,"href":"https:\/\/baldsolutions.com\/index.php\/wp-json\/wp\/v2\/posts\/733\/revisions\/780"}],"wp:attachment":[{"href":"https:\/\/baldsolutions.com\/index.php\/wp-json\/wp\/v2\/media?parent=733"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/baldsolutions.com\/index.php\/wp-json\/wp\/v2\/categories?post=733"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/baldsolutions.com\/index.php\/wp-json\/wp\/v2\/tags?post=733"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}