Course contentsShow
← C
Lesson 1146 of 1,21915. Systems ProgrammingFree lesson

Lock-free programming concepts

Lock-free programming concepts

What you'll learn: How to design algorithms where threads progress without ever being forced to wait for a mutual exclusion lock.

The problem with locks

In standard multithreading, we use mutexes to protect shared data. If Thread A holds a lock, Thread B is "blocked"—it goes to sleep and waits for its turn. This is simple, but it can lead to problems like deadlocks (where threads wait on each other forever) or priority inversion (where a slow thread holds up a fast one).

What is "Lock-free"?

An algorithm is lock-free if, at any point in time, at least one thread in the system is making progress. Unlike a mutex, where everyone might be stuck waiting for a crashed thread to release a lock, a lock-free system ensures the system as a whole keeps moving.

Think of a busy four-way stop versus a roundabout. At a four-way stop (a lock), cars must stop and wait for their turn. If a driver falls asleep at the sign, the whole intersection stalls. In a roundabout (lock-free), traffic keeps flowing. Even if one car slows down, others can navigate around the circle.

The Compare-and-Swap (CAS) Loop

Lock-free programming relies on "atomic primitives" instead of locks. The most common is Compare-and-Swap (CAS). Instead of saying "Lock this, change it, unlock it," we say: "Here is the old value I saw, and here is the new value I want. If the value is still what I think it is, swap them. If not, I’ll try again."

Here is how we might increment a shared counter without a single pthread_mutex_lock:

#include <stdatomic.h>

void atomic_increment(atomic_int *counter) {
    int old_value = atomic_load(counter);
    int new_value;

    do {
        new_value = old_value + 1;
        // atomic_compare_exchange_weak returns true if swap succeeded.
        // If another thread changed 'counter' in the meantime, 
        // it updates 'old_value' with the current reality and we loop again.
    } while (!atomic_compare_exchange_weak(counter, &old_value, new_value));
}

Why use it?

Lock-free programming is incredibly fast for high-concurrency systems, like interrupt handlers or real-time audio processing, where you cannot afford to let a thread go to sleep. However, it is much harder to write and debug than lock-based code. You are trading simplicity for raw, unblocked performance.

Key takeaway

Lock-free programming uses atomic operations like CAS to ensure that at least one thread is always making progress, eliminating the bottlenecks and risks of traditional mutexes.