Thanks alot for your responses guys. Out of using volatile, Interlocked and
lock, which option has a better performance, if the shared resource is a
primitive type ?
Thanks,
Ramesh
> > Are primitive types like bool threadsafe ? Or do we need to use
> > synchronization when multiple threads concurrently access a value type ?
[quoted text clipped - 12 lines]
>
> Pete
Peter Duniho - 22 Apr 2008 18:33 GMT
> Thanks alot for your responses guys. Out of using volatile, Interlocked
> and
> lock, which option has a better performance, if the shared resource is a
> primitive type ?
"One of those things is not like the others". :)
The "volatile" keyword is not a synchronization construct. It simply
ensures that there's a "memory barrier" to ensure that if one thread has
executed code to write to the variable, that another thread executing code
to read from the variable will see what's written.
If you want synchronization, you need a synchronization object. For
access to simple primitives, the Interlocked class is your best bet
there. Note, however, that the Interlocked class doesn't support the bool
type. Typically this is addressed by using an integer type as a boolean.
Pete
Jon Skeet [C# MVP] - 22 Apr 2008 19:17 GMT
> Thanks alot for your responses guys. Out of using volatile, Interlocked and
> lock, which option has a better performance, if the shared resource is a
> primitive type ?
Peter's answer is entirely correct, but doesn't cover one aspect: are
you really sure you need the most performant result? When it comes to
threading, I value correctness *much* higher than performance for
almost all cases. I find it much easier to reason about a lock than
about a volatile variable.
How many times are you expecting to access this variable every second?

Signature
Jon Skeet - <skeet@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
World class .NET training in the UK: http://iterativetraining.co.uk