使用这个关键字,可以防止将变量存到寄存器中,达到编译器优化,每次都从内存中读取变量的值。
volatile bool是否是线程安全的呢?
volatile
can be used for such purposes. However this is an extension to standard C++ by Microsoft:
Microsoft Specific
Objects declared as volatile are (...)
- A write to a volatile object (volatile write) has Release semantics; (...)
- A read of a volatile object (volatile read) has Acquire semantics; (...)
This allows volatile objects to be used for memory locks and releases in multithreaded applications.(emph. added)
That is, as far as I understand, when you use the Visual C++ compiler, a volatile bool
is for most practical purposes an atomic<bool>
.
atomic<bool>。