Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

atomic_t in Linux

I'm studying Linux kernel with Linux Kernel Development by Robert Love.

As you know, this book uses old version of Linux. It's in 2.6 version

atomic_t has "volatile int counter". But newly Linux version's atomic_t has "int counter" not volatile. Why this volatile has erased?

like image 612
A.Cho Avatar asked Jan 12 '16 15:01

A.Cho


People also ask

What is Atomic_t?

The atomic_t type in the Linux kernel is a simple integer variable with a set of operations which are guaranteed to be atomic without the need for explicit locking.

What is atomic operation in Linux?

The Linux kernel uses a large variety of "atomic" operations — operations that are indivisible as observed from anywhere within the system — to provide safe and efficient behavior in a multi-threaded environment.

What is Atomic_read?

atomic_read. This function atomically reads the value of the given atomic variable. int atomic_read(atomic_t *v); where, v – pointer of type atomic_t.

How are atomic operations handled in Linux?

Atomic operations on the other hand provide instructions which complete in one instruction cycle. Since atomic instructions complete in one single instruction cycle, they are not interrupted by other CPUs trying to access the same memory location. This prevents race conditions.


1 Answers

Because volatile variables are not atomic variables. The only point in using volatile is to prevent possible compiler optimisations, which is not the same as preventing unwanted concurrent access.

In that regard, the use of volatile is almost never correct.

You can read more about it in Semantics and Behavior of Atomic and Bitmask Operations.

Quoting a small part of it:

* 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! *

like image 119
jweyrich Avatar answered Oct 02 '22 03:10

jweyrich