Linux Kernel Programming - atomic_t datatype - atomic variables and APIs
Linux Kernel Programming - atomic_t datatype - atomic variables and APIs

If you allocate any global variables and when you access them (i.e read or write) at different parts of the code you are supposed to use locks such as Spinlocks, Mutexes, etc quite obviously to avoid race conditions. If you fail to use locks then there is a high possibility of unreliable (corrupt) data read, writes and even leading to kernel crashes. Of course if the data-structure or data-types of these global variables is huge and complex such as struct, arrays, etc, then we should use locks.

But if you intend to use simple data-types then most of the times you can just use atomic_t Atomic variables and its respective provided APIs. Refer the provided Linux Kernel source links below of the source-code of atomic_t data-types. The advantages of using these atomic variables is that you never need extra set of binding locks to protect those variables during read and write operations. Atomic variables ensures serialization thus avoiding race conditions unlike normal regular C data-types.

Here is my detailed YouTube video on the same:

Refer:
https://elixir.bootlin.com/linux/latest/A/ident/atomic_t
https://elixir.bootlin.com/linux/latest/source/include/linux/types.h#L177
https://elixir.bootlin.com/linux/latest/source/arch/x86/include/asm/atomic.h

I also conduct sessions/classes on Systems and Network Software Programming, Linux Kernel Programming and Architecture. If you are interested, click HERE for more details.

If you have any queries or anything to discuss further on Linux Kernel Programming and writing Kernel modules kindly feel free to contact me.