Skip to main content

Command Palette

Search for a command to run...

Critical Section|Exclusive execution|Atomicity

Updated
2 min read
Critical Section|Exclusive execution|Atomicity

A critical section is a piece of code where shared data is accessed.

Only one thread should execute this area at a time. Multiple CPUs and multiple kernel threads may access the same memory at the same time.

A spinlock allows only one thread or CPU core at a time to enter a critical section. If another thread tries to acquire the lock while it's already held, it repeatedly checks ("spins") until the lock becomes available.

spin_lock(&my\_lock);

/* Critical section */
shared_variable++;

spin_unlock(&my_lock);

Why spin?

Unlike a mutex, a thread waiting on a spinlock does not sleep. Instead, it continuously loops: This avoids the overhead of putting a thread to sleep and waking it up, making spinlocks useful when:

The lock is expected to be held for a very short time. Sleeping is not allowed (e.g., interrupt context in the kernel). Multiple CPU cores may access the same data

spinlock_t is an opaque type; kernel code normally manipulates it through APIs such as

An opaque type hides its implementation details from users of the API. Users can:

Declare variables of the type. Pass them to functions. Store pointers to them.

But they should not rely on the internal layout.

Exclusive execution means:

A task or code runs in a way that ensures no other execution context interferes at all during its execution window.

This is a broader guarantee than a critical section.

It can apply to:

entire functions kernel threads CPUs/cores interrupt contexts

mutex_lock(&mylock);
 code... 
mutex_unlock(&mylock)

Atomicity Operation completes entirely or not at all.

No one can see a half-finished update.

atomic_read(&counter);
  1. atomic.h → HEADER (gives tools)
  2. atomic_t → DATA TYPE (stores value)
  3. atomic_inc → OPERATION (modifies value safely)

Source Code

The complete source code for this article is available on GitHub:

linux_kernel_sync4 Repository