Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Under C# is Int64 use on a 32 bit processor dangerous

I read in the MS documentation that assigning a 64-bit value on a 32-bit Intel computer is not an atomic operation; that is, the operation is not thread safe. This means that if two people simultaneously assign a value to a static Int64 field, the final value of the field cannot be predicted.

Three part question:

  • Is this really true?
  • Is this something I would worry about in the real world?
  • If my application is multi-threaded do I really need to surround all my Int64 assignments with locking code?
like image 340
Noah Avatar asked Feb 27 '09 18:02

Noah


3 Answers

This is not about every variable you encounter. If some variable is used as a shared state or something (including, but not limited to some static fields), you should take care of this issue. It's completely non-issue for local variables that are not hoisted as a consequence of being closed over in a closure or an iterator transformation and are used by a single function (and thus, a single thread) at a time.

like image 180
mmx Avatar answered Sep 28 '22 10:09

mmx


Even if the writes were atomic, chances are you would still need to take out a lock whenever you accessed the variable. If you didn't do that, you'd at least have to make the variable volatile to make sure that all threads saw the new value the next time they read the variable (which is almost always what you want). That lets you do atomic, volatile sets - but as soon as you want to do anything more interesting, such as adding 5 to it, you'd be back to locking.

Lock free programming is very, very hard to get right. You need to know exactly what you're doing, and keep the complexity to as small a piece of code as possible. Personally, I rarely even try to attempt it other than for very well known patterns such as using a static initializer to initialize a collection and then reading from the collection without locking.

Using the Interlocked class can help in some situations, but it's almost always a lot easier to just take out a lock. Uncontested locks are "pretty cheap" (admittedly they get expensive with more cores, but so does everything) - don't mess around with lock-free code until you've got good evidence that it's actually going to make a significant difference.

like image 23
Jon Skeet Avatar answered Sep 28 '22 10:09

Jon Skeet


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.

But also:

As with any other type, reading and writing to a shared variable that contains an instance of this type must be protected by a lock to guarantee thread safety.

like image 40
eljenso Avatar answered Sep 28 '22 09:09

eljenso