c# 线程同步问题(about volatile)

本文深入探讨了并发编程中的核心概念,包括volatile关键字的理解与正确使用、Barrier同步原语的应用及ReaderWriterLockSlim与传统ReaderWriterLock的区别。通过多个实例与官方文档链接,帮助读者掌握这些关键同步机制。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

这个古老的话题,

这里是一个大杂烩;

首先让我们看stackoverflow中一个经典的问题:

Volatile vs. Interlocked vs. lock

 

然后连接看答案:

https://stackoverflow.com/questions/154551/volatile-vs-interlocked-vs-lock

这里的误区,主要是对volatile的解释和使用;

关于volatile的解释和示例:

http://www.jaylee.org/post/2004/08/05/Dont-get-C-volatile-the-wrong-way.aspx

 

这里还有一篇较好的文章:

http://igoro.com/archive/volatile-keyword-in-c-memory-model-explained/ (这篇文章讲得非常好,非常好,强烈推荐)

一些文字摘要:

The memory model is a fascinating topic – it touches on hardware, concurrency, compiler optimizations, and even math.

The memory model defines what state a thread may see when it reads a memory location modified by other threads. For example, if one thread updates a regular non-volatile field, it is possible that another thread reading the field will never observe the new value. This program never terminates (in a release build):

 

这里我们再进行  synchronization  中 Barrier 的使用;

 

https://msdn.microsoft.com/en-us/library/system.threading.barrier(v=vs.110).aspx (微软官网示例方法)

它的另外一种用法滴啊;

How to: Synchronize Concurrent Operations with a Barrier

https://docs.microsoft.com/en-us/dotnet/standard/threading/how-to-synchronize-concurrent-operations-with-a-barrier

还有这个例子:

http://dotnetpattern.com/threading-barrier

 

 

这里关于 readerwriterlockslim  and  readerwritelock 之间的基本区别;

ReaderWriterLockSlim is similar to ReaderWriterLock, but it has simplified rules for recursion and for upgrading and downgrading lock state. 

ReaderWriterLockSlimavoids many cases of potential deadlock. In addition, the performance of ReaderWriterLockSlim is significantly better than ReaderWriterLockReaderWriterLockSlim is recommended for all new development.

 

关于readerWriterLockSlim 是文章:

https://msdn.microsoft.com/en-us/library/system.threading.readerwriterlockslim.aspx

 

关于c#同步机制的一个总结:

https://docs.microsoft.com/en-us/dotnet/standard/threading/overview-of-synchronization-primitives

 

转载于:https://www.cnblogs.com/mc67/p/7474345.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值