Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Int64 (long) and Thread Safety

A quote from MSDN

Assigning an instance of this type is not thread safe on all hardware platforms because the binary representation of that instance might be too large to assign in a single atomic operation.

Does it mean is that Thead-safe on 64bit processors like Itianium or x86-64 as well?

For instance:

long data = GetData();
// some parallel task on data

Could be a problem?

like image 620
Lukasz Madon Avatar asked Oct 14 '22 02:10

Lukasz Madon


2 Answers

Possibly, but why would you write a program that will be thread safe on some Intel workalike platforms, but not others? Note that the Decimal and Double types also have this disclaimer about thread safety.

Microsoft recommends the use of locks in these cases. There are links to some good information about concurrency, memory mapping and low-level locks here:

http://social.msdn.microsoft.com/Forums/en-US/csharpgeneral/thread/f03ea3c9-4c2b-4a79-8f8c-4a6b7476b20d

like image 165
Robert Harvey Avatar answered Oct 21 '22 04:10

Robert Harvey


Memory load/store operations are considered to be atomic if they are performed on memory chunks that are placed on aligned memory address and are not bigger than the native machine-sized pointer.
Meaning, at 64bit load/store operation on an aligned memory address will be atomic on a 64bit platform, but it won't be atomic on a 32bit platform.

Modern processors offers a special set of instructions (in .Net, most of them are exposed via the Interlocked class). that allow to achieve atomicity on load/store operations that are larger than the machine's native pointer size (64bit operations on 32bit processors, and 128bit operations on 64bit processors. The latter isn't exposed by the Interlocked class, but is available in native code).

For more details, check Joe Duffy's post: Thread-safety, torn reads, and the like.

like image 23
Liran Avatar answered Oct 21 '22 04:10

Liran