Using C/Pthreads: do shared variables need to be volatile?

前端 未结 13 910
迷失自我
迷失自我 2020-11-28 06:03

In the C programming language and Pthreads as the threading library; do variables/structures that are shared between threads need to be declared as volatile? Assuming that t

13条回答
  •  死守一世寂寞
    2020-11-28 06:35

    NO.

    Volatile is only required when reading a memory location that can change independently of the CPU read/write commands. In the situation of threading, the CPU is in full control of read/writes to memory for each thread, therefore the compiler can assume the memory is coherent and optimizes the CPU instructions to reduce unnecessary memory access.

    The primary usage for volatile is for accessing memory-mapped I/O. In this case, the underlying device can change the value of a memory location independently from CPU. If you do not use volatile under this condition, the CPU may use a previously cached memory value, instead of reading the newly updated value.

提交回复
热议问题