.NET:CLR via C# The Interlocked Anything Pattern
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的更多相关文章
- 设计模式:空对象模式(Null Object Pattern)
设计模式:空对象模式(Null Object Pattern) 背景 群里聊到<ASP.NET设计模式>,这本书里有一个“Null Object Pattern”,大家就闲聊了一下这个模式 ...
- 第一节:CLR寄宿
本系列文章来自 CLR VIA C# .NET FrameWork在Microsoft Windows平台的顶部运行.这意味着.NET必须用Windows可以理解的技术来构建.首先,所有的托管模块和 ...
- 解决“ 故障模块名称: clr.dll ”
错误内容: 微软的错误说明:http://support.microsoft.com/kb/2640103/zh-cn 类似下面的错误: 错误应用程序名称:xxx.exe,版本: 1.0.0.0,时间 ...
- CLR via C#读书笔记一:CLR的执行模型
CLR(Common Language Runtime)公共语言进行时是一个可由多种编程语言使用的“进行时”. 将源代码编译成托管模块 可用支持CLR的任何语言创建源代码文件,然后用对应的编译器检查语 ...
- .NET:CLR via C# User-Mode Constructs
The CLR guarantees that reads and writes to variables of the following data types are atomic: Boolea ...
- .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 ...
- .NET:CLR via C# Compute-Bound Asynchronous Operations
线程槽 使用线程池了以后就不要使用线程槽了,当线程池执行完调度任务后,线程槽的数据还在. 测试代码 using System; using System.Collections.Generic; us ...
- .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 ...
- [C#] 类型学习笔记一:CLR中的类型,装箱和拆箱
在学习.NET的时候,因为一些疑问,让我打算把.NET的类型篇做一个总结.总结以三篇博文的形式呈现. 这篇博文,作为三篇博文的第一篇,主要探讨了.NET Framework中的基本类型,以及这些类型一 ...
随机推荐
- Asis CTF 2015-Car_Market
恰好找到了这道题的bin文件,就来做一下. 这道题目是一个经典的选单程序但是具有三级选单,在bss段存在指针数组ptr,ptr中的值指向每个主结构,其中主结构如下所示. [] model [] pri ...
- SqlServr性能优化性能之层次结构(十五)
1.添加根节点: hierarchyid GetRoot()方法 --创建数据库 create table Employeeh(EmployeeID int,Name varchar(500),Ma ...
- git clone 某个分支或者所有分支
clone 某个分支: git clone -b dev5 https://git.coding.net/aiyongbao/tradepc.git clone 所有分支: git cl ...
- pytest mark中的skip,skipif, xfail
这些测试的过滤,或是对返回值的二重判断, 可以让测试过程更精准,测试结果更可控, 并可以更高层的应用测试脚本来保持批量化执行. import pytest import tasks from task ...
- CCF CSP 201409-4 最优配餐
CCF计算机职业资格认证考试题解系列文章为meelo原创,请务必以链接形式注明本文地址 CCF CSP 201409-4 最优配餐 问题描述 栋栋最近开了一家餐饮连锁店,提供外卖服务.随着连锁店越来越 ...
- (转)最短路算法--Dijkstra算法
转自:http://blog.51cto.com/ahalei/1387799 上周我们介绍了神奇的只有五行的Floyd最短路算法,它可以方便的求得任意两点的最短路径,这称为“多源最短 ...
- Springboot以war包方式运行
一. 修改打包形式 在pom.xml里设置 <packaging>war</packaging> 二.添加以下依赖 提供标记嵌入式servlet容器 <depen ...
- JMS开发指南
1.JMS消息的异步与同步接收 消息的异步接收: 异步接收是指当消息到达时,主动通知客户端,即当消息到达时转发到客户端.JMS客户端可以通过注册一个实现MessageListener接口的对象到Mes ...
- BZOJ.2916.[POI1997]Monochromatic Triangles(三元环)
题目链接 \(Description\) n个点的完全图,其中有m条边用红边相连,其余边为蓝色.求其中三边同色的三角形个数. \(Solution\) 直接求同色 除了n^3 不会.. 三角形总数是C ...
- BZOJ 4066 简单题(KD树)
[题目链接] http://www.lydsy.com/JudgeOnline/problem.php?id=4066 [题目大意] 要求维护矩阵内格子加点和矩阵查询 [题解] 往KD树上加权值点,支 ...