Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I use atomic or volatile for pointers?

Tags:

c++

volatile

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.

like image 989
balki Avatar asked Apr 11 '12 18:04

balki


2 Answers

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.

like image 101
Mark Ransom Avatar answered Sep 21 '22 10:09

Mark Ransom


volatile is useless for multithreading, so that option is out. You indeed just want an atomic variable.

like image 45
GManNickG Avatar answered Sep 20 '22 10:09

GManNickG