atomic_t 在 Linux
atomic_t in Linux
我正在研究 Linux 内核 Linux Robert Love 的内核开发。
如您所知,本书使用旧版本Linux。 2.6版本
atomic_t 有 "volatile int counter"。但是新 Linux 版本的 atomic_t 有 "int counter" 不可变。为什么这个 volatile 被抹掉了?
因为volatile变量不是原子变量。使用 volatile
的唯一一点是防止可能的编译器优化,这与防止不需要的并发访问不同。
在这方面,volatile
的使用几乎从来都不正确。
您可以在 Semantics and Behavior of Atomic and Bitmask Operations 中阅读更多相关信息。
引用其中一小部分:
* WARNING: atomic_read() and atomic_set() DO NOT IMPLY BARRIERS! *
Some architectures may choose to use the volatile keyword, barriers, or inline
assembly to guarantee some degree of immediacy for atomic_read() and
atomic_set(). This is not uniformly guaranteed, and may change in the future,
so all users of atomic_t should treat atomic_read() and atomic_set() as simple
C statements that may be reordered or optimized away entirely by the compiler
or processor, and explicitly invoke the appropriate compiler and/or memory
barrier for each use case. Failure to do so will result in code that may
suddenly break when used with different architectures or compiler
optimizations, or even changes in unrelated code which changes how the
compiler optimizes the section accessing atomic_t variables.
* YOU HAVE BEEN WARNED! *
我正在研究 Linux 内核 Linux Robert Love 的内核开发。
如您所知,本书使用旧版本Linux。 2.6版本
atomic_t 有 "volatile int counter"。但是新 Linux 版本的 atomic_t 有 "int counter" 不可变。为什么这个 volatile 被抹掉了?
因为volatile变量不是原子变量。使用 volatile
的唯一一点是防止可能的编译器优化,这与防止不需要的并发访问不同。
在这方面,volatile
的使用几乎从来都不正确。
您可以在 Semantics and Behavior of Atomic and Bitmask Operations 中阅读更多相关信息。
引用其中一小部分:
* WARNING: atomic_read() and atomic_set() DO NOT IMPLY BARRIERS! *
Some architectures may choose to use the volatile keyword, barriers, or inline assembly to guarantee some degree of immediacy for atomic_read() and atomic_set(). This is not uniformly guaranteed, and may change in the future, so all users of atomic_t should treat atomic_read() and atomic_set() as simple C statements that may be reordered or optimized away entirely by the compiler or processor, and explicitly invoke the appropriate compiler and/or memory barrier for each use case. Failure to do so will result in code that may suddenly break when used with different architectures or compiler optimizations, or even changes in unrelated code which changes how the compiler optimizes the section accessing atomic_t variables.
* YOU HAVE BEEN WARNED! *