1. 程式人生 > >c# 線程同步問題(about volatile)

c# 線程同步問題(about volatile)

har www. observe asp wro modified link 我們 cat

這個古老的話題,

首先讓我們看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

c# 線程同步問題(about volatile)