C# memory barrier and the volatile and lock memory barrier attribnute

本文探讨了内存屏障的概念及其在多线程编程中的作用。内存屏障是一种同步机制,确保所有读写操作在特定条件下完成。文章详细解释了锁(lock)和易失(volatile)关键字如何创建不同类型的内存屏障。

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

Memory barrier is a synchornization mechanism where all operation (read and/or write) must hold until certain conditions occurs (e.g. when some variable finish writing, or finishi reading, or more than one thread reach one point)...

 

C# may or may not have the memory barriers interfaces (this require more research work), however, in this topic, we are goiong to focus on the semantics of memory barrier and how the lock and volatile related to the memory barriers.

 

 

as may be pointted out by this post - Memory Barriers by lock statement

 

Brian Giedon - http://stackoverflow.com/users/158779/brian-gideon 写道
The subject of memory barriers is quite complex. It even trips up the experts from time to time. When we talk about a memory barrier we are really combining two different ideas.

* Acquire fence: A memory barrier in which other reads & writes are not allowed to move before the fence.
* Release fence: A memory barrier in which other reads & writes are not allowed to move after the fence.
A memory barrier that creates only one of two is sometimes called a half-fence. A memory barrier that creates both is sometimes called a full-fence.

The volatile keyword creates half-fences. Reads of volatile fields have acquire semantics while writes have release semantics. That means no instruction can be moved before a read or after a write.

The lock keyword creates full-fences on both boundaries (entry and exit). That means no instruction can be moved either before or after each boundary.

However, all of this moot if we are only concerned with one thread. Ordering, as it is perceived by that thread, is always preserved. In fact, without that fundamental guarentee no program would ever work right. The real issue is with how other threads perceive reads and writes. That is where you need to be concerned.

So to answer your questions:

1. From a single thread's perspective...yes. From another thread's perspective...no.

2. It depends. That might work, but I need to have better understanding of what you are trying to acheive.

3. From another thread's perspective...no. The reads and writes are free to move around within the boundaries of the lock. They just cannot move outside those boundaries. That is why it is important for other threads to also create memory barriers.

 

NOTE:

 

there may be more content following this discusion.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值