There are two threads (t1 and t2) pinned to two different cores. They both have a shared variable which is a raw pointer to some class type. t1 only reads the pointer and t2 reads/writes the pointer. Should I declare the pointer as just volatile or atomic or both?
When t2 updates this pointer, it is fine if t1 reads the old one or new one but it should not read any intermediate value as it will cause seg fault.
volatile
is useful for telling the compiler not to optimize out repeated accesses to the memory used by a variable. Obviously you'll want this if another thread could be updating the variable. The reason it's called "almost useless" is that in too many cases this is not sufficient to guarantee proper multi-threaded behavior and you'll need to look at memory fences and atomic primitive operations.
On some processor architectures such as Intel, a read or write to an integer or pointer will be atomic as long as it's properly memory aligned. See for example http://software.intel.com/en-us/forums/showpost.php?p=31711 Intel links keep changing so I wasn't able to find the definitive resource.
volatile
is useless for multithreading, so that option is out. You indeed just want an atomic variable.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With