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. ubuntu14.04 使用传统的netcat

    Ubuntu上默认安装的是netcat-openbsd,而不是经典的netcat-traditional. 网上例子很多都是以netcat-traditional为例. sudo apt-get -y ...

  2. git clone 某个分支或者所有分支

    clone 某个分支: git clone -b  dev5   https://git.coding.net/aiyongbao/tradepc.git clone 所有分支:   git   cl ...

  3. 【LOJ】#2032. 「SDOI2016」游戏

    题解 看错题了,以为单次修改相当于一个覆盖,后来才明白"添加"-- 就相当于添加很多线段求最小值 首先这个等差数列添加的方式比较烦人,我们拆开两条链,一条s到lca,一条lca到t ...

  4. 【LOJ】#2290. 「THUWC 2017」随机二分图

    题解 看了一眼觉得是求出图对图统计完美匹配的个数(可能之前做过这样模拟题弃疗了,一直心怀恐惧... 然后说是统计一下每种匹配出现的概率,也就是,当前左边点匹配状态为S,右边点匹配状态为T,每种匹配出现 ...

  5. LoadRunner FAQ

    LoadRunner FAQ web_concurrent_start和web_concurrent_end web_concurrent_start 语法: int web_concurrent_s ...

  6. 【Java】 int与String类型间的相互转化

    public class Test { public static void main(String[] args) { /* * int类型转String类型 */ int n1 = 9; //1. ...

  7. CentOS 配置自启动Redis

    第一步: 在/etc/init.d/目录下建立一个名字为 redis 的启动脚本 cd /etc/init.d touch redis 然后在这个脚本中添加如下脚本  <注意修改自己的PIDFI ...

  8. mysql proxy代理安装和配置

    mysql proxy代理安装和配置 服务器说明: 192.168.1.219   mysql主库(主从复制) 192.168.1.177   mysql从库(主从复制) 192.168.1.202 ...

  9. CODEVS 4655 序列终结者-splay(区间更新、区间翻转、区间最值)

    4655 序列终结者  时间限制: 1 s  空间限制: 128000 KB  题目等级 : 大师 Master 题解       题目描述 Description 网上有许多题,就是给定一个序列,要 ...

  10. Bunch 转换为 HDF5 文件:高效存储 Cifar 等数据集

    关于如何将数据集封装为 Bunch 可参考 关于 『AI 专属数据库的定制』的改进. PyTables 是 Python 与 HDF5 数据库/文件标准的结合.它专门为优化 I/O 操作的性能.最大限 ...