Tuesday, February 05, 2008

Is object assignment statement thread safe?

It really depends on the type of the assignment.

" The CLR guarantees that for types which are no bigger than the size of a native integer, if the memory is properly aligned (as it is by default - if you specify an explicit layout, that could change the alignment), reads and writes are atomic. In other words, if one thread is changing a properly aligned int variable's value from 0 to 5 and another thread is reading the variable's value, it will only ever see 0 or 5 - never 1 or 4, for instance. For a long, however, on a 32-bit machine, if one thread is changing the value from 0 to 0x0123456789abcdef, there's no guarantee that another thread won't see the value as 0x0123456700000000 or 0x0000000089abcdef. You'd have to be unlucky - but writing thread-safe code is all about taking luck out of the equation."

From link

It does not mention object reference assignment. However the size of object reference is always equal to the native integer which means on 32-bit machine the reference size should be 32 bits and on 64-bit machine the reference size should always be 64 bits, therefore it is thread safe.

No comments: