Many people look at the Interlocked methods and wonder why Microsoft doesn't create a richer set of interlocked methods that can be used in a wider range of scenarios. For example, it would be nice if the Interlocked class offered Multiply, Divide, Minimum, Maximum, And, Or, Xor, and a bunch of other methods. Although the Interlocked class doesn’t offer these methods, there is a well-known pattern that allows you to perform any operation on an Int32 in an atomic way by using Interlocked.CompareExchange. In fact, because Interlocked.CompareExchange has additional overloads that operate on Int64, Single, Double, Object, and a generic reference type, this pattern will actually work for all these types, too.

This pattern is similar to optimistic concurrency patterns used for modifying database records. Here is an example of the pattern that is being used to create an atomic Maximum method.

Now let me explain exactly what is going on here. Upon entering the method, currentVal is initialized to the value in target at the moment the method starts executing. Then, inside the loop, startVal is initialized to this same value. Using startVal, you can perform any operation you want. This operation can be extremely complex, consisting of thousands of lines of code. But, ultimately, you must end up with a result that is placed into desiredVal. In my example, I simply determine whether startVal or value contains the larger value.

Now, while this operation is running, another thread could change the value in target. It is unlikely that this will happen, but it is possible. If this does happen, then the value in desiredVal is based off an old value in startVal, not the current value in target, and therefore, we should not change the value in target. To ensure that the value in target is changed to desiredVal if no thread has changed target behind our thread’s back, we use Interlocked.CompareExchange. This method checks whether the value in target matches the value in startVal (which identifies the value that we thought was in target before starting to perform the operation). If the value in target didn’t change, then CompareExchange changes it to the new value in desiredVal. If the value in target did change, then CompareExchange does not alter the value in target at all.

CompareExchange returns the value that is in target at the time when CompareExchange is called, which I then place in currentVal. Then, a check is made comparing startVal with the new value in currentVal. If these values are the same, then a thread did not change target behind our thread’s back, target now contains the value in desiredVal, the while loop does not loop around, and the method returns. If startVal is not equal to currentVal, then a thread did change the value in target behind our thread’s back, target did not get changed to our value in desiredVal, and the while loop will loop around and try the operation again, this time using the new value in currentVal that reflects the other thread’s change.

Personally, I have used this pattern in a lot of my own code and, in fact, I made a generic method, Morph, which encapsulates this pattern.

.NET:CLR via C# The Interlocked Anything Pattern的更多相关文章

  1. 设计模式:空对象模式(Null Object Pattern)

    设计模式:空对象模式(Null Object Pattern) 背景 群里聊到<ASP.NET设计模式>,这本书里有一个“Null Object Pattern”,大家就闲聊了一下这个模式 ...

  2. 第一节:CLR寄宿

    本系列文章来自 CLR VIA C# .NET FrameWork在Microsoft  Windows平台的顶部运行.这意味着.NET必须用Windows可以理解的技术来构建.首先,所有的托管模块和 ...

  3. 解决“ 故障模块名称: clr.dll ”

    错误内容: 微软的错误说明:http://support.microsoft.com/kb/2640103/zh-cn 类似下面的错误: 错误应用程序名称:xxx.exe,版本: 1.0.0.0,时间 ...

  4. CLR via C#读书笔记一:CLR的执行模型

    CLR(Common Language Runtime)公共语言进行时是一个可由多种编程语言使用的“进行时”. 将源代码编译成托管模块 可用支持CLR的任何语言创建源代码文件,然后用对应的编译器检查语 ...

  5. .NET:CLR via C# User-Mode Constructs

    The CLR guarantees that reads and writes to variables of the following data types are atomic: Boolea ...

  6. .NET:CLR via C# Primitive Thread Synchronization Constructs

    User-Mode Constructs The CLR guarantees that reads and writes to variables of the following data typ ...

  7. .NET:CLR via C# Compute-Bound Asynchronous Operations

    线程槽 使用线程池了以后就不要使用线程槽了,当线程池执行完调度任务后,线程槽的数据还在. 测试代码 using System; using System.Collections.Generic; us ...

  8. .NET:CLR via C# The CLR’s Execution Model

    The CLR’s Execution Model The core features of the CLR memory management. assembly loading. security ...

  9. [C#] 类型学习笔记一:CLR中的类型,装箱和拆箱

    在学习.NET的时候,因为一些疑问,让我打算把.NET的类型篇做一个总结.总结以三篇博文的形式呈现. 这篇博文,作为三篇博文的第一篇,主要探讨了.NET Framework中的基本类型,以及这些类型一 ...

随机推荐

  1. CVE-2009-3459

     Adobe Acrobat和Reader都是美国Adobe公司开发的非常流行的PDF文件阅读器.         Adobe Reader和Acrobat 7.1.4之前的7.x版本,8.1.7之前 ...

  2. 安装部署Apache Hadoop (本地模式和伪分布式)

    本节内容: Hadoop版本 安装部署Hadoop 一.Hadoop版本 1. Hadoop版本种类 目前Hadoop发行版非常多,有华为发行版.Intel发行版.Cloudera发行版(CDH)等, ...

  3. Linux的bash快捷键

    Ctrl-A 相当于HOME键,用于将光标定位到本行最前面 Ctrl-E 相当于End键,即将光标移动到本行末尾 Ctrl-B 相当于左箭头键,用于将光标向左移动一格 Ctrl-F 相当于右箭头键,用 ...

  4. 【LOJ】#2040. 「SHOI2015」零件组装机

    题解 我写的应该有bug但是我懒得改了 就是最后一次合并的n要么是0点边集的最后一条边,要么是0点边集最后两条边的差,我们分别拎出来判断一下哪个可行(也许两个都可行,但是我不想多做修改了--) 然后递 ...

  5. linux kernel.shmall shemax shemin解释

        Linux X86-64操作系统,Oracle 10g数据库,由8G加到16G,把kernel.shmmax参数改到17179869184(16G)后,发现只要修改sga_max_size和s ...

  6. express增加swagger功能

    参考地址:https://blog.csdn.net/freeboy1234/article/details/79289486 下载swagger ui库 地址是:https://github.com ...

  7. CSUOJ 1040 Round-number

    Description Most of the time when rounding a given number, it is customary to round to some multiple ...

  8. windows上springboot打war部署tomcat小记

    web项目,需要部署到云主机里去,现在windows里试一下. springboot项目,主要流程就只是打成war包后扔到tomcat里去,但是由于是springboot项目,有一些需要注意的地方,这 ...

  9. iOS 11开发教程(十一)了解iOS11应用视图

    iOS 11开发教程(十一)了解iOS11应用视图 在iPhone或者iPad中,用户看到的和摸到的都是视图.视图是用户界面的重要组成元素.本节将主要讲解视图的添加.删除以及位置和大小的设置等内容. ...

  10. DNS隧道工具iodine

    DNS隧道工具iodine   在受限制的网络中,如果DNS请求没有被限制,就可以通过DNS请求建立隧道而突破网络限制.iodine是Kali Linux提供的一款DNS隧道工具.该工具分为服务器端i ...