Why is this assignment not thread safe?

I read this book from Joseph Albahari about streaming:
http://www.albahari.com/threading/

In Part 2, I found this example:
http://www.albahari.com/threading/part2.aspx#_When_to_Lock

Here is the above example:

class ThreadUnsafe { static int _x; static void Increment() { _x++; } static void Assign() { _x = 123; } } 

Version for version:

 class ThreadSafe { static readonly object _locker = new object(); static int _x; static void Increment() { lock (_locker) _x++; } static void Assign() { lock (_locker) _x = 123; } } 

I could not understand why the Assign method is not thread safe. Should the integer assignment be atomic on both 32-bit and 64-bit architectures?

+8
multithreading c # thread-safety locking
source share
1 answer

The destination is atomic, since any read stream will either see 123, or the previous value is not some kind of intermediate value. However, there is no guarantee that the stream will see the new value until there are two memory barriers: a write write barrier in the write stream and a read barrier in the read stream.

If you had two threads similar to this (after creating _x public or internal so that it could be read from other course types - or with code in the ThreadSafe class):

 // Thread 1 Console.WriteLine("Writing thread starting"); ThreadSafe.Assign(); Console.WriteLine("Writing thread done"); // Thread 2 Console.WriteLine("Reading thread starting"); while (ThreadSafe._x != 123) { // Do nothing } Console.WriteLine("Reading thread done"); 

... there is no guarantee that thread 2 will never end because thread 2 cannot "see" the destination from thread 1.

+9
source share

All Articles