Changeable as a synchronization mechanism

Say I have a class Foo and it has a static member variable called Count (type is integer). This variable was used in a multi-threaded application, and I used the lock synchronization mechanism before doing any read / write operations for this variable. Since I am reading this Volatile article, I get the impression that I can remove all locks around this variable and just use the volatile keyword when declaring this variable. This should take care of all things related to synchronization. It's right? What are the pros and cons of this approach?

+5
source share
3 answers

I can remove all locks around this variable and just use the volatile keyword when declaring this variable. This should take care of all things related to synchronization. It's right?

May be. Probably no. Getting the right multi-threaded code is extremely difficult. It is best to use multi-threaded code with a low level of lock for experts.

What are the pros and cons of this approach?

The upside is that it can be several nanoseconds faster to avoid blocking. Finishes, if you program incorrectly with a low lock level, then your program looks as if it is working fine and then has fancy failure modes that cannot be debugged or played back.

, , , . , , , , . , CLR, , .

. , , , , .

+8

, , , volatile, , . (.. ) , - .

, :

Count = Count + 1;

, : , , . . , Count .

  • 1 Count ( 0)
  • Thread 2 Count ( 0)
  • Thread 1 (1)
  • Thread 1 write Count ( 1)
  • Thread 2 (1)
  • Thread 2 write Count ( 1)

Count 1, 2.

Interlocked. , Interlocked.Increment Interlocked.CompareExchange.

+4

volatile lock. A lock , , , , , , . volatile , , , . , , , , . volatile tells the compiler not to consider such optimizations and always read your variable value from memory, not from a cached register.

John Skeet discusses this in more detail in his article , Volatility, Atomicity, and Blocking.

+1
source

All Articles