Should ALL global variables be volatile-qualified?

后端 未结 5 1227
走了就别回头了
走了就别回头了 2020-12-31 09:48

In this example, does correctness require global_value to be declared volatile?

int global_value = 0;

void foo () {
    ++ global_v         


        
5条回答
  •  甜味超标
    2020-12-31 10:40

    No. Global variables should not always be declared volatile.

    You only really need it to be volatile if it could be changed by other threads and may suffer from memory reordering issues or compiler instruction reordering. And even then you won't need it if you have appropriate mutexing. Typically though, you probably have a bad design if you need to mutex global variables.

    EDIT: making it volatile does not mean that the global variable would be thread safe though!

    Other typical uses might be where the memory is accessed in an unusual way - for example if you have some DMA mapped memory on an embedded micro.

提交回复
热议问题