What kinds of optimizations does 'volatile' prevent in C++?

后端 未结 8 1730
Happy的楠姐
Happy的楠姐 2020-11-27 17:04

I was looking up the keyword volatile and what it\'s for, and the answer I got was pretty much:

It\'s used to prevent the compiler from o

相关标签:
8条回答
  • 2020-11-27 17:42

    Condition variables are not where volatile is needed; strictly it is only needed in device drivers.

    volatile guarantees that reads and writes to the object are not optimized away, or reordered with respect to another volatile. If you are busy-looping on a variable modified by another thread, it should be declared volatile. However, you shouldn't busy-loop. Because the language wasn't really designed for multithreading, this isn't very well supported. For example, the compiler may move a write to a non-volatile variable from after to before the loop, violating the lock. (For indefinite spinloops, this might only happen under C++0x.)

    When you call a thread-library function, it acts as a memory fence, and the compiler will assume that any and all values have changed — essentially everything is volatile. This is either specified or tacitly implemented by any threading library to keep the wheels turning smoothly.

    C++0x might not have this shortcoming, as it introduces formal multithreading semantics. I'm not really familiar with the changes, but for the sake of backward compatibility, it doesn't require to declare anything volatile that wasn't before.

    0 讨论(0)
  • 2020-11-27 17:42

    Volatile doesn't try to keep data to a cpu register (100's of times faster than memory). It has to read it from memory every time it is used.

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