Should I use atomic or volatile for pointers?

There are two threads (t1 and t2) attached to two different cores. They both share a common variable, which is a raw pointer to some type of class. t1 only reads the pointer, and t2 reads / writes the pointer. Should I declare a pointer as just mutable or atomic or both?

When t2 updates this pointer, it is normal if t1 reads old or new, but it should not read any intermediate value, as this will cause seg to fail.

+6
source share
2 answers

volatile is useful for telling the compiler not to optimize repeated accesses to the memory used by the variable. Obviously, you will need this if another thread can update the variable. The reason he called “almost useless” is that in too many cases this is not enough to guarantee the correct multi-threaded behavior, and you will need memory observations and atomic primitive operations.

On some processor architectures, such as Intel, reading or writing to an integer or pointer will be atomic if it is correctly aligned in memory. See for example http://software.intel.com/en-us/forums/showpost.php?p=31711 . Intel links continue to change, so I could not find the final resource.

+6
source

volatile useless for multithreading, so the option is missing. You really want to get an atomic variable.

+3
source

Source: https://habr.com/ru/post/912964/


All Articles