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. 大数据统计分析平台之三、Kibana安装和使用

    kibana安装 1.到官网下载kibana: cd /usr/local/software wget https://artifacts.elastic.co/downloads/kibana/ki ...

  3. C#和PHP 长整型时间互转

    //2018/5/14 16:03:05转换:1526284985 public static double ConvertToDouble(DateTime date) { , , )); var ...

  4. XUtils开源框架的使用(HttpUtils支持多线程断点续传)

    XUtils项目下载地址:https://github.com/wyouflf/xUtils XUtils中包含的四大模块: 1.DbUtils模块 2.ViewUtils模块 3.HttpUtils ...

  5. poj2492 A Bug's Life(带权并查集)

    题目链接 http://poj.org/problem?id=2492 题意 虫子有两种性别,有n只虫子,编号1~n,输入m组数据,每组数据包含a.b两只虫子,表示a.b为不同性别的虫子,根据输入的m ...

  6. Eclipse daemon not running. starting it now on port ***的

    daemon not running. starting it now on port ***的 1) 运行 cmd,进入命令行2) 输入 netstat -ano ,找出占用端口***(port * ...

  7. 有了这套flex页面布局方案,页面什么的,那都不是事。

    一.CSS3弹性盒子弹性盒子是CSS3的一种新布局模式.CSS3 弹性盒( Flexible Box 或 flexbox),是一种当页面需要适应不同的屏幕大小以及设备类型时确保元素拥有恰当的行为的布局 ...

  8. HDU - 1022 Train Problem I STL 压栈

    Train Problem I Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others) ...

  9. 机器学习之路: 深度学习 tensorflow 神经网络优化算法 学习率的设置

    在神经网络中,广泛的使用反向传播和梯度下降算法调整神经网络中参数的取值. 梯度下降和学习率: 假设用 θ 来表示神经网络中的参数, J(θ) 表示在给定参数下训练数据集上损失函数的大小. 那么整个优化 ...

  10. tomcat启动startup.bat一闪而过的问题处理方式

    tomcat在启动时,会读取环境变量的信息,需要一个CATALINA_HOME 与JAVA_HOME的信息,CATALINA_HOME即tomcat的主目录,JAVA_HOME即Java安装的主目录, ...