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

The need for atomic operations

The need for atomic operations

What you'll learn: Why standard variables fail in multi-threaded environments and how "race conditions" create unpredictable bugs.

The Illusion of a Single Step

In C, a simple line of code like count++; looks like one action. However, when the computer executes this, it actually performs three distinct steps:

  1. Read: Pull the value of count from memory into a CPU register.
  2. Modify: Add 1 to that value inside the register.
  3. Write: Store the new value back into memory.

In a single-threaded program, this is invisible. But in systems programming, where multiple threads run simultaneously, these steps can be interrupted.

The Coffee Pot Analogy

Imagine two roommates, Alice and Bob, sharing a coffee pot that tracks "cups brewed."

  1. Alice sees there are 10 cups brewed. She decides to add one.
  2. Just as Alice is about to write "11" on the log, Bob walks in.
  3. Bob also sees the number 10 (because Alice hasn't updated it yet).
  4. Bob adds 1 and writes "11."
  5. Alice finishes her thought and also writes "11."

Even though two people added a cup, the counter only went up by one. This is a race condition. The final result depends on the "race" between threads and who finishes their read-modify-write cycle first.

Code in Conflict

Without atomic operations, shared variables become unreliable. Even if you run this code multiple times, you might get a different answer every time.

#include <stdio.h>
#include <pthread.h>

int shared_counter = 0;

void* increment(void* arg) {
    for (int i = 0; i < 100000; i++) {
        // This is NOT atomic. Multiple threads can 
        // read the same old value at the same time.
        shared_counter++;
    }
    return NULL;
}

int main() {
    pthread_t t1, t2;
    pthread_create(&t1, NULL, increment, NULL);
    pthread_create(&t2, NULL, increment, NULL);
    
    pthread_join(t1, NULL);
    pthread_join(t2, NULL);

    // Expected: 200000. Actual: Likely much less (e.g., 143202)
    printf("Final count: %d\n", shared_counter);
    return 0;
}

Why Atomics Matter

Atomic operations solve this by ensuring a task is "indivisible." When an operation is atomic, the CPU guarantees that the Read-Modify-Write cycle happens as one single, uninterruptible unit. No other thread can see the variable in a halfway state. If we want our systems to be thread-safe and data to be accurate, we must move beyond standard types to atomic ones.

Key takeaway

Standard operations are not thread-safe because they take multiple CPU steps; atomic operations ensure these steps happen as one inseparable action.