Are primitive types like bool threadsafe ?

  • Thread starter Thread starter Ramesh
  • Start date Start date
R

Ramesh

Are primitive types like bool threadsafe ? Or do we need to use
synchronization when multiple threads concurrently access a value type ?

Thanks,
Ramesh
 
Are primitive types like bool threadsafe ? Or do we need to use
synchronization when multiple threads concurrently access a value type ?

Thanks,
Ramesh


Yes they are handled atomically. But use volatile defining it. It says the
compiler not to do any optimizations for the state of the variable.

private volatile bool _atom;
 
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
 
Ramesh said:
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?
 
Back
Top