Why is volatile keyword not needed for thread synchronisation?

前端 未结 4 959
轮回少年
轮回少年 2021-01-17 10:41

I am reading that the volatile keyword is not suitable for thread synchronisation and in fact it is not needed for these purposes at all.

While I unders

4条回答
  •  梦毁少年i
    2021-01-17 11:04

    Making the answer even shorter, not using either a mutex or a semaphore, is a bug. As soon as thread B releases the mutex (and thread A gets it), any value in the register which contains the shared variable's value from thread B are guaranteed to be written to cache or memory that will prevent a race condition when thread A runs and reads this variable.

    The implementation to guarantee this is architecture/compiler dependent.

提交回复
热议问题