Why is volatile keyword not needed for thread synchronisation?

前端 未结 4 951
轮回少年
轮回少年 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条回答
  •  伪装坚强ぢ
    2021-01-17 10:56

    Shortening the answer already given, you do not need to use volatile with mutexes for a simple reason:

    • If compiler knows what mutex operations are (by recognizing pthread_* functions or because you used std::mutex), it well knows how to handle access in regards to optimization (which is even required for std::mutex)
    • If compiler does not recognize them, pthread_* functions are completely opaque to it, and no optimizations involving any sort of non-local duration objects can go across opaque functions

提交回复
热议问题