Interlocked:为多个线程共享的变量提供原子操作。

Interlocked.Increment(ref value) 数值加一(原子性操作)
Interlocked.Decrement(ref value) 数值减一(原子性操作)
Interlocked.Exchange(ref value1, value2) 交换:把值2赋给值1;返回原值
Interlocked.CompareExchange(ref value1, value2, value3) 实现比较和交换两种功能:值1和值3比较,如果相同,把值2给值1,不相同则不作任何操作;返回原值(多用于判断条件)(示例3中会用到)
  • 实现原子级运算
 int increament = ;
Thread th1 = new Thread(() =>
{
for (int i = ; i < ; i++)
Console.WriteLine($"th1 {Interlocked.Increment(ref increament)}");
}); Thread th2 = new Thread(() =>
{
for (int i = ; i < ; i++)
Console.WriteLine($"th2 {Interlocked.Increment(ref increament)}");
}); Thread th3 = new Thread(() =>
{
for (int i = ; i < ; i++)
Console.WriteLine($"th3 {Interlocked.Increment(ref increament)}");
}); Thread th4 = new Thread(() =>
{
for (int i = ; i < ; i++)
Console.WriteLine($"th4 {Interlocked.Increment(ref increament)}");
}); th1.Start();
th2.Start();
th3.Start();
th4.Start();
Console.ReadKey();

实现递增计算

运行结果:

 int increament = ;
Thread th1 = new Thread(() =>
{
for (int i = ; i < ; i++)
//Console.WriteLine($"th1 {Interlocked.Increment(ref increament)}");
Console.WriteLine($"th1 {increament++}");
}); Thread th2 = new Thread(() =>
{
for (int i = ; i < ; i++)
//Console.WriteLine($"th2 {Interlocked.Increment(ref increament)}");
Console.WriteLine($"th2 {increament++}");
}); Thread th3 = new Thread(() =>
{
for (int i = ; i < ; i++)
//Console.WriteLine($"th3 {Interlocked.Increment(ref increament)}");
Console.WriteLine($"th3 {increament++}");
}); Thread th4 = new Thread(() =>
{
for (int i = ; i < ; i++)
//Console.WriteLine($"th4 {Interlocked.Increment(ref increament)}");
Console.WriteLine($"th4 {increament++}");
}); th1.Start();
th2.Start();
th3.Start();
th4.Start();
Console.ReadKey();

非原子并行计算

  • 模拟锁

用Exchange函数实现锁

         //0 for false, 1 for true.
private static int usingResource = ;
//A simple method that denies reentrancy.
static bool UseResource()
{
//0 indicates that the method is not in use.
if ( == Interlocked.Exchange(ref usingResource, ))
{
Console.WriteLine("{0} acquired the lock", Thread.CurrentThread.Name); //Code to access a resource that is not thread safe would go here. //Simulate some work
Thread.Sleep(); Console.WriteLine("{0} exiting lock", Thread.CurrentThread.Name); //Release the lock
Interlocked.Exchange(ref usingResource, );
return true;
}
else
{
Console.WriteLine(" {0} was denied the lock", Thread.CurrentThread.Name);
return false;
}
}

用Exchange模拟锁

用CompareExchange函数实现锁

         private double totalValue = 0.0;

         public double Total { get { return totalValue; } }

         public double AddToTotal(double addend)
{
double initialValue, computedValue;
do
{
initialValue = totalValue;//---(1)
computedValue = initialValue + addend;//---(2) }
while (initialValue != Interlocked.CompareExchange(ref totalValue,
computedValue, initialValue));
//Interlocked.CompareExchange:比较totalValue与initialValue是否相同,如果相同,则用computedValue的值覆盖totalValue //如果totalValue与initialValue值不相同,则说明在(1)与(2)步骤执行的同时,
//其他线程执行了对totalValue进行了改变
return computedValue;
}

CompareExchange模拟锁

原子操作参考:http://www.cnblogs.com/5iedu/p/4719625.html

[.net 多线程] Interlocked实现CAS操作的更多相关文章

  1. CPU的CAS操作

    https://blog.csdn.net/qq_35492857/article/details/78471032 https://www.cnblogs.com/gdjdsjh/p/5076815 ...

  2. 【Java并发编程实战】-----“J.U.C”:CAS操作

    CAS,即Compare and Swap,中文翻译为"比较并交换". 对于JUC包中,CAS理论是实现整个java并发包的基石.从整体来看,concurrent包的实现示意图如下 ...

  3. Go并发编程之美-CAS操作

    摘要: 一.前言 go语言类似Java JUC包也提供了一些列用于多线程之间进行同步的措施,比如低级的同步措施有 锁.CAS.原子变量操作类.相比Java来说go提供了独特的基于通道的同步措施.本节我 ...

  4. 具体CAS操作实现(无锁算法)

    具体CAS操作 上一篇讲述了CAS机制,这篇讲解CAS具体操作. 什么是悲观锁.乐观锁?在java语言里,总有一些名词看语义跟本不明白是啥玩意儿,也就总有部分面试官拿着这样的词来忽悠面试者,以此来找优 ...

  5. 深入浅出 Java Concurrency (5): 原子操作 part 4 CAS操作

    在JDK 5之前Java语言是靠synchronized关键字保证同步的,这会导致有锁(后面的章节还会谈到锁). 锁机制存在以下问题: (1)在多线程竞争下,加锁.释放锁会导致比较多的上下文切换和调度 ...

  6. Java乐观锁实现之CAS操作

    介绍CAS操作前,我们先简单看一下乐观锁 与 悲观锁这两个常见的锁概念. 悲观锁: 从Java多线程角度,存在着“可见性.原子性.有序性”三个问题,悲观锁就是假设在实际情况中存在着多线程对同一共享的竞 ...

  7. 无锁的同步策略——CAS操作详解

    目录 1. 从乐观锁和悲观锁谈起 2. CAS详解 2.1 CAS指令 2.3 Java中的CAS指令 2.4 CAS结合失败重试机制进行并发控制 3. CAS操作的优势和劣势 3.1 CAS相比独占 ...

  8. 锁、CAS操作和无锁队列的实现

    https://blog.csdn.net/yishizuofei/article/details/78353722 锁的机制 锁和人很像,有的人乐观,总会想到好的一方面,所以只要越努力,就会越幸运: ...

  9. 多线程之:java的CAS操作的相关信息

    一:锁机制存在的性能问题? 在JDK 5之前Java语言是靠synchronized关键字保证同步的,这会导致有锁(后面的章节还会谈到锁). 锁机制存在以下问题:(1)在多线程竞争下,加锁.释放锁会导 ...

随机推荐

  1. NoSuchBeanDefinitionException: No bean named 'shiroFilter' is defined

    以前运行正常的项目,过了一段时间再运行时出问题,打开链接无反应,无法访问Tomcat,空白页面. 经检查发现,在Tomcat log中有报错: NoSuchBeanDefinitionExceptio ...

  2. Git使用点滴记录: You have no permission to access this repo.

    代码托管在https://coding.net上面,之前Git用https的方式都好好的,没有出什么问题.结果今天git pull代码的时候一直提示以下信息: remote: Coding.net T ...

  3. android欢迎页

    在进入程序后,会在一个页面停留几秒然后自动跳转到程序主界面,这个页面就是欢迎页. 首先新建个java文件,给他起名叫做WelcomeActivity 在里面我们通过一个匿名类new Handler,在 ...

  4. oracle自动创建表分区

    创建一个table,记录哪些表需要创建表分区 create table STAT_TABLE ( tablename VARCHAR2(), pre_partition_name VARCHAR2() ...

  5. Linux - 文件合并

    >:左边命令的结果覆盖右边文件的内容 cat 命令,把文件的内容覆盖另一个文件中的内容 把两个文件的内容合并到一个文件中 echo 命令 whoami 命令 >>:把左边命令执行的结 ...

  6. python's sixth day for me

    ---恢复内容开始--- #  ==  比较的是数值 a = 1000 b = 1000 print(a == b) #True #  is 比较的是内存地址 >>> a = 100 ...

  7. springboot成神之——发送邮件

    本文介绍如何用spring发送邮件 目录结构 依赖 MailConfig TestController 测试 本文介绍如何用spring发送邮件 目录结构 依赖 <dependency> ...

  8. MAPREDUCE原理篇2

    mapreduce的shuffle机制 概述: mapreduce中,map阶段处理的数据如何传递给reduce阶段,是mapreduce框架中最关键的一个流程,这个流程就叫shuffle: shuf ...

  9. sendMail在centos下的安装

    一.sendEmail介绍   SendEmail is a lightweight, command line SMTP email client. If you have the need to ...

  10. CSV Format

    [CSV Format] The comma separated values format (CSV) has been used for exchanging and converting dat ...