Introduction to Kernel Synchronization
Critical Section or Critical Region (CS/CR): The piece of code that manipulates shared data. It can be evoked multiple times by competing threads.
If CS/CR is not executed atomically, it can lead to race condition. And it will lead to race condition in multi-threaded, concurrent execution case.
Synchronization is ensuring that race condition does not occur.
Processor ensures that the atomic instructions are never interleaved. It is physically impossible to have interleaving atomic instructions.
General purpose processors do not, and must not, support arbitrarily sized atomic instructions or CS/CR.
If a thread is already executing in CS/CR, a lock will prevent access of CS/CR by another thread .
There are many types of locks available and their classification depends upon what they do when they need to obtain a lock, that has already been acquired by another thread.
There are two main types:
1. One type that busy-waits, and
2. Another type that blocks.
Locks are acquired and released using atomic instructions, otherwise, locking and unlocking would itself become a race.
Following are the things that might interrupt currently executing code:
1. Interrupts: Interrupt handlers, Softirqs, tasklets etc.
2. Kernel preemption
3. Scheduler and
where, SMP is symmetric multiprocessing.
When does concurrency hurts?
1. When a kernel code preempts, while in CS/CR.
2. Kernel code blocks.
3. An IH accessing share-able data of the interrupted process, and
4. Two or more threads accessing CS/CR without synchronization.
You can make your code interrupt-safe, SMP-safe, and preemption-safe.
Data on the stack of a function is probably safe.
And always go bye the diction, "Lock data. Not code."
Post in production.
This post is based upon chapter 9 of the book, Linux Kernel Development by Robert Love, IIIrd edition.