Are volatile variable 'reads' as fast as normal reads?

前端 未结 5 2012
攒了一身酷
攒了一身酷 2020-11-30 05:35

I know that writing to a volatile variable flushes it from the memory of all the cpus, however I want to know if reads to a volatile variable are as fast as nor

5条回答
  •  臣服心动
    2020-11-30 06:11

    It is architecture dependent. What volatile does is tell the compiler not to optimise that variable away. It forces most operations to treat the variable's state as an unknown. Because it is volatile, it could be changed by another thread or some other hardware operation. So, reads will need to re-read the variable and operations will be of the read-modify-write kind.

    This kind of variable is used for device drivers and also for synchronisation with in-memory mutexes/semaphores.

提交回复
热议问题