Safe to use volatile bool to force another thread to wait? (C++)

后端 未结 5 1623
醉话见心
醉话见心 2021-02-08 18:52

Everything I\'ve read about volatile says it\'s never safe, but I still feel inclined to try it, and I haven\'t seen this specific scenario declared unsafe.

I have a sep

5条回答
  •  栀梦
    栀梦 (楼主)
    2021-02-08 18:52

    There are three issues that C++11 atomics address.

    First, a thread switch can occur in the middle of reading or writing a value; for reads, another thread could update the value before the original thread reads the rest of the value; for writing, another thread could see the half-written value. This is known as "tearing".

    Second, in a typical multi-processor system, each processor has its own cache, and it reads and writes values to that cache; sometimes the cache and main memory are updated to ensure that they hold the same values, but until a processor that writes a new value flushes its cache and a thread that reads the value reloads its copy from the cache the value can be different. This is referred to as "cache coherency".

    Third, the compiler can move code around, and store one value before it stores another, even if the code is written in the opposite order. As long as you can't write a valid program that can see the difference, that's okay under the "as if" rule.

    Loading from and storing to an atomic variable (with the default memory-ordering) prevents all three problems. Marking a variable as volatile does not.

    EDIT: don't bother figuring out which architectures pose which problems. The author of the standard library has already done this for the architecture that the library implementation is intended for. Don't look for shortcuts; just use atomics. You won't lose anything.

提交回复
热议问题