Is this rule about volatile usage strict?

前端 未结 8 1763
梦毁少年i
梦毁少年i 2020-12-11 20:36

I\'ve seen this sentence:

the general rule is, if you have variables of primitive type that must be shared among multiple threads, declare those

相关标签:
8条回答
  • 2020-12-11 21:31

    Read this. Volatile has nothing to do with multi-threading.

    0 讨论(0)
  • 2020-12-11 21:31

    I would say that in theory those rules are absolutely right, and volatile is needed every time when a variable is accessed by 2 threads. (Even when using mutexes, cause they don't prevent compiler optimizations.) But in practice compilers are good enough at recognizing situations where a variable might be modified outside a particular function so that its value shouldn't be cached in registers. In most cases volatile is not necessary.

    I once did some testing in MSVC by inspecting the assembler output for different situations, and all it took to prevent a variable from being cached was to have another function writing to the same variable or taking its address. Global variables were never optimized unless "whole program optimization" was turned on (so the compiler can be sure the variable is not modified in other translation units).

    0 讨论(0)
提交回复
热议问题