Is volatile bool for thread control considered wrong?

前端 未结 5 2141
我寻月下人不归
我寻月下人不归 2020-11-30 03:45

As a result of my answer to this question, I started reading about the keyword volatile and what the consensus is regarding it. I see there is a lot of informat

5条回答
  •  余生分开走
    2020-11-30 04:25

    This will work for your case but to protect a critical section this approach is wrong. If it were right then one could use a volatile bool in almost all cases where a mutex is used. The reason for it is that a volatile variable does not guarantee enforcing any memory barriers nor any cache coherence mechanism. On the contrary, a mutex does. In other words once a mutex is locked a cache invalidation is broadcast to all cores in order to maintain consistency among all cores while. With volatile this is not the case. Nevertheless, Andrei Alexandrescu proposed a very interesting approach to use volatile to enforce synchronization on a shared object. And as you'll see he does it with a mutex; volatile is only used to prevent accessing the object's interface without synchronization.

提交回复
热议问题