The volatile qualifier tells the compiler to avoid certain optimizations because the object’s value can change in unexpected ways.
CPU registers are not shared between threads or CPU’s, meaning that Thread #1 would probably never know about changes Thread #2 made and vice versa.
With the volatile qualifier in use, however, the compiler should not cache variable in a CPU register and should instead fetch it from and write it to memory each time it is accessed.
volatile int x;
Write 1 to x
Write 2 to x
Use of volatile would only slowdown performance. Use volatile if mutex is not used.
If the variable you are using is a simple data type (i.e. int, bool) you do not need a mutex. If you do not use a mutex you must use volatile.
If the variable is complex (ie std::string, std::vector) you must use a mutex, if there is any possibility at all that the variable will be updated while another thread is trying to access it.
Don’t try to use volatile variables as a way to synchronize , it won’t work reliably.