Back to series
· 17 min read

What is thread safety? How do locks and synchronization mechanisms work?


I. What Is Thread Safety?

Thread safety means that a program, object, or function still behaves correctly when multiple threads access it at the same time, and does not produce corrupted data, abnormal state, or unpredictable results due to differences in thread execution order.

Simply put:

No matter how multiple threads interleave their execution, the program should satisfy the expected business rules.

For example, multiple threads operating on the same bank account:

balance = 1000

def withdraw(amount):
    global balance
    balance -= amount

Suppose two threads execute at the same time:

withdraw(100)

According to the business logic, the final balance should be:

1000 - 100 - 100 = 800

But in actual execution, the final balance may not be 800.

The reason is that balance -= 100 is not an indivisible operation; it involves multiple steps such as reading, computing, and writing.

If both threads read the balance as 1000, they may both compute 900 and then both write 900.

The final result:

Expected balance: 800
Actual balance: 900

This kind of problem is a typical thread-safety issue.

II. Why Does Multithreading Produce Thread-Safety Problems?

1. Threads share process resources

Multiple threads in the same process share most of the process's resources, such as:

  • Heap memory.
  • Global variables.
  • Static variables.
  • File descriptors.
  • Open files and network connections.
  • Shared objects in the process address space.

Each thread usually has its own thread stack, register context, and thread-local storage, but it can access the shared data in the process.

For example:

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

int counter = 0;

void* increment(void* arg) {
    for (int i = 0; i < 100000; i++) {
        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);

    printf("counter = %d\n", counter);

    return 0;
}

The program creates two threads, and each thread performs the increment 100000 times.

Theoretical result:

counter = 200000

But the actual result may be less than 200000.

Because the two threads modify the shared variable counter at the same time, a data race occurs.

2. Thread scheduling is nondeterministic

The operating system scheduler decides when a thread runs, how long it runs, and when it switches to another thread.

The order in which threads execute may be affected by the following factors:

  • Number of CPU cores.
  • Thread priority.
  • Time slice allocation.
  • System load.
  • I/O blocking.
  • Interrupts and context switches.
  • Compiler and CPU instruction reordering.

For example, two threads perform the following operations:

Thread A: read counter
Thread A: counter + 1
Thread A: write counter

Thread B: read counter
Thread B: counter + 1
Thread B: write counter

The actual execution may interleave like this:

Initial counter = 0

Thread A: read counter, gets 0
Thread B: read counter, gets 0
Thread A: compute 0 + 1
Thread B: compute 0 + 1
Thread A: write 1
Thread B: write 1

Final counter = 1

Both threads performed the increment once, but the final result is only 1.

3. Thread execution order is not the same as the order in which the code is written

The code a programmer writes is usually arranged in order, but during actual execution, the compiler and CPU may reorder instructions to improve execution efficiency.

For example:

a = 1;
b = 2;

Provided the constraints of the language memory model are satisfied, the compiler or CPU may adjust the order in which instructions are executed.

In a single-threaded scenario, this kind of optimization usually does not change the observable behavior of the program.

But in a multithreaded scenario, if appropriate synchronization mechanisms are lacking, other threads may observe unexpected states.

Therefore, thread safety involves not only multiple threads accessing data at the same time, but also how threads correctly coordinate execution order and memory visibility.

III. Race Conditions and Data Races

There are two very important concepts in thread-safety issues: race conditions and data races.

1. Race Condition

A race condition means that the result of a program's execution depends on the unpredictable execution order among multiple threads or execution units.

For example:

if account.balance >= amount:
    account.balance -= amount

Suppose the account balance is 100, and two threads try to withdraw 80 at the same time.

The following may happen:

Thread A: Read balance 100
Thread B: Read balance 100
Thread A: Determine balance is sufficient
Thread B: Determine balance is sufficient
Thread A: Deduct 80
Thread B: Deduct 80

Both threads believe the balance is sufficient, yet an over-deduction ultimately occurs.

The problem is not merely a read/write conflict on a certain variable, but the lack of correct concurrency control for the entire business operation.

2. Data Race

A data race generally refers to:

  • Two or more threads concurrently access the same memory location.
  • At least one access is a write operation.
  • There is no synchronization relationship between the accesses that satisfies the language memory model.

For example:

int counter = 0;

void* worker(void* arg) {
    counter++;
    return NULL;
}

If multiple threads execute counter++ at the same time without using locks or atomic operations, a data race may occur.

In C and C++, unsynchronized non-atomic data races lead to undefined behavior.

This means the compiler can optimize based on the assumption that no data race exists, so you cannot simply assume the program is merely occasionally miscalculating.

3. What Is the Difference Between the Two?

Comparison Dimension Race Condition Data Race
Focus Program result depends on execution timing Concurrent memory access lacks synchronization
Scope Business logic and execution order Memory access behavior
Whether it necessarily involves shared variables Not necessarily Usually involves shared memory locations
Whether it is necessarily a language-level error Not necessarily Depends on the language memory model
Typical problems Duplicate orders, over-deduction Multiple threads writing a variable concurrently

Note the following:

  • A data race may lead to a race condition.
  • A race condition does not necessarily come from a data race.
  • Even without a data race, concurrency errors may still exist in business logic.

For example, two threads each call a thread-safe inventory query API and then each performs an order-placement operation. If the query and deduction are not a single atomic business operation, overselling can still occur.

4. Typical Process Leading to a Race Condition

flowchart TD
    A["Multiple threads start executing"] --> B["Access shared resources"]
    B --> C["Perform reads or checks"]
    C --> D["Thread execution orders interleave"]
    D --> E["Read stale or identical state"]
    E --> F["Perform modification operations separately"]
    F --> G["Shared state becomes incorrect"]
    G --> H["A race condition occurs"]

    style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
    style B fill:#DCEFE5,stroke:#8EBFA5,color:#24563F
    style C fill:#EDE7F8,stroke:#B9A4DC,color:#514174
    style D fill:#FFF3D6,stroke:#E7C77D,color:#75551D
    style E fill:#FFF3D6,stroke:#E7C77D,color:#75551D
    style F fill:#DCEFE5,stroke:#8EBFA5,color:#24563F
    style G fill:#FCE7E7,stroke:#E5A3A3,color:#8A3636
    style H fill:#FCE7E7,stroke:#E5A3A3,color:#8A3636

4. What Is a Critical Section?

A critical section is a region of code that accesses shared resources and requires concurrency protection.

For example:

counter++;

If counter is a variable shared by multiple threads, then the code that modifies it belongs to a critical section.

A typical critical section includes:

  1. Accessing shared resources.
  2. Checking shared state.
  3. Modifying shared state.
  4. Updating related data structures.

For example, bank account deduction:

def withdraw(account, amount):
    if account.balance >= amount:
        account.balance -= amount

The entire check-and-deduction process should be protected, not just the final assignment.

1. What Conditions Must a Critical Section Satisfy?

Classic concurrency theory usually discusses critical sections from the following aspects:

Mutual Exclusion

At any given time, at most one thread is allowed to enter a critical section protected by mutual exclusion.

Progress

When no thread occupies the critical section and some thread wishes to enter, the system must not arbitrarily prevent all threads from entering.

Bounded Waiting

After a thread requests to enter the critical section, it should not wait indefinitely, and other threads must not be able to take precedence an unlimited number of times.

These are the theoretical requirements of the classic critical section problem. Whether an actual lock implementation satisfies strict fairness still depends on the design of the specific lock.

2. Basic Structure of a Critical Section

flowchart TD
    A["Thread prepares to access shared resource"] --> B["Request to enter critical section"]
    B --> C{"Is access permission obtained?"}
    C -->|Yes| D["Enter critical section"]
    C -->|No| E["Wait or retry"]
    E --> B
    D --> F["Read or modify shared data"]
    F --> G["Exit critical section"]
    G --> H["Release access permission"]

    style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
    style B fill:#DCEFE5,stroke:#8EBFA5,color:#24563F
    style C fill:#FFF3D6,stroke:#E7C77D,color:#75551D
    style D fill:#EDE7F8,stroke:#B9A4DC,color:#514174
    style E fill:#FCE7E7,stroke:#E5A3A3,color:#8A3636
    style F fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
    style G fill:#DCEFE5,stroke:#8EBFA5,color:#24563F
    style H fill:#DCEFE5,stroke:#8EBFA5,color:#24563F

5. What is a lock? Why can it guarantee thread safety?

A lock is a synchronization mechanism used to restrict multiple threads from accessing shared resources at the same time.

A thread needs to acquire the lock before entering the critical section, and release the lock after completing the operation.

When a thread holds a mutex, other threads competing for the same lock cannot enter the critical section protected by that lock at the same time.

1. Mutex Lock

A mutex (Mutual Exclusion Lock) is the most common thread synchronization mechanism.

Basic operations:

  • lock(): Acquire the lock.
  • unlock(): Release the lock.

Example:

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

int counter = 0;

pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;

void* increment(void* arg) {
    for (int i = 0; i < 100000; i++) {
        pthread_mutex_lock(&mutex);

        counter++;

        pthread_mutex_unlock(&mutex);
    }

    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);

    printf("counter = %d\n", counter);

    pthread_mutex_destroy(&mutex);

    return 0;
}

Now, before each execution of counter++, a thread must first acquire the mutex.

Therefore, the two threads cannot enter this protected critical section at the same time.

The final result should be:

counter = 200000

2. How does a lock work?

A mutex can be thought of as an access permit with ownership.

Suppose there are two threads:

  • Thread A.
  • Thread B.

Both need to access a shared variable.

Execution process:

flowchart TD
    A["Thread A requests the lock"] --> B{"Is the lock free?"}
    B -->|Yes| C["Thread A acquires the lock"]
    B -->|No| D["Thread A waits"]
    C --> E["Thread A enters the critical section"]
    E --> F["Modify shared data"]
    F --> G["Thread A releases the lock"]
    G --> H["Waiting threads compete for the lock"]
    H --> I["Thread B acquires the lock"]
    I --> J["Thread B enters the critical section"]
    J --> K["Complete operations on shared data"]
    K --> L["Thread B releases the lock"]

    style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
    style B fill:#FFF3D6,stroke:#E7C77D,color:#75551D
    style C fill:#DCEFE5,stroke:#8EBFA5,color:#24563F
    style D fill:#FCE7E7,stroke:#E5A3A3,color:#8A3636
    style E fill:#EDE7F8,stroke:#B9A4DC,color:#514174
    style F fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
    style G fill:#DCEFE5,stroke:#8EBFA5,color:#24563F
    style H fill:#FFF3D6,stroke:#E7C77D,color:#75551D
    style I fill:#DCEFE5,stroke:#8EBFA5,color:#24563F
    style J fill:#EDE7F8,stroke:#B9A4DC,color:#514174
    style K fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
    style L fill:#DCEFE5,stroke:#8EBFA5,color:#24563F

Note that a lock does not mean that only one thread can run in the entire program; rather, it restricts the critical section protected by the same lock.

Other code that does not compete for the same lock can still execute concurrently.

3. Underlying Implementation Principles of Locks

Mutexes are usually implemented using atomic operations provided by hardware.

Common atomic instructions include:

  • Test-and-Set.
  • Compare-and-Swap, or CAS for short.
  • Exchange.
  • Fetch-and-Add.

Taking CAS as an example, its core logic is:

CAS(memory address, expected value, new value)

This means:

It changes the value at the specified memory location to the new value only if the current value equals the expected value.

The comparison and modification are completed as one indivisible atomic operation.

Pseudocode:

bool compare_and_swap(int* ptr, int expected, int desired) {
    if (*ptr == expected) {
        *ptr = desired;
        return true;
    }

    return false;
}

Note that this is only pseudocode used to explain the principle, not a truly thread-safe CAS implementation. A real implementation must use hardware atomic instructions or the atomic operation interfaces provided by the language.

A simplified spinlock can be expressed as follows:

#include <stdatomic.h>
#include <stdbool.h>

typedef struct {
    atomic_bool locked;
} SpinLock;

void spin_lock(SpinLock* lock) {
    while (atomic_exchange(&lock->locked, true)) {
        // Keep trying to acquire the lock
    }
}

void spin_unlock(SpinLock* lock) {
    atomic_store(&lock->locked, false);
}

Where:

  • atomic_exchange() atomically reads and sets the lock state.
  • If the original state is false, the current thread successfully acquires the lock.
  • If the original state is true, the lock is already held, and the thread continues to wait.
  • atomic_store() restores the lock state to unlocked.

This is a simplified implementation for teaching purposes. In real engineering, memory ordering, processor cache contention, waiting strategies, and lock fairness also need to be considered.

4. Spinlocks and Mutexes

Both types of locks can provide mutual exclusion, but they wait in different ways.

Spinlock

When a thread cannot acquire the lock, it does not go to sleep immediately; instead, it continuously tries to acquire the lock in a loop.

while (locked) {
    // Busy waiting
}

Advantages:

  • It does not require frequent thread sleeping and waking.
  • When the critical section is very short, it may have lower waiting overhead.
  • It is commonly used in kernels and low-level concurrency scenarios.

Disadvantages:

  • It continuously occupies the CPU while waiting.
  • It wastes computational resources when lock contention is severe.
  • If the thread holding the lock is scheduled out, waiting threads may spin idle for a long time.

Mutex

When a thread cannot acquire the lock, it can usually enter a blocked waiting state, with the operating system or runtime handling scheduling.

Advantages:

  • Waiting usually does not require continuously occupying the CPU.
  • Suitable for critical sections that may last for a long time.
  • Can avoid a large number of threads busy-waiting continuously.

Disadvantages:

  • May involve thread blocking and wake-up.
  • Has scheduling and context-switching overhead.
Comparison aspect Spinlock Mutex
Waiting behavior Busy waiting Usually blocking wait
CPU consumption Continuously consumed while waiting Usually not continuously consumed while blocked
Acquisition failure Continues retrying May enter a wait queue
Applicable scenarios Extremely short critical sections Longer critical sections or unpredictable contention
Typical cost CPU spinning Blocking, wake-up, and scheduling

Not all mutexes necessarily trigger a system call. Modern runtimes and operating systems usually use a user-space fast path, brief spinning, and blocking mechanisms when necessary.

6. Common Lock Types and Their Differences

In addition to ordinary mutexes, there are various locks and synchronization primitives.

1. Reentrant Lock

A reentrant lock is also called a recursive lock.

It allows the same thread to acquire the same lock repeatedly without permanently blocking itself due to repeated acquisition.

For example:

import threading

lock = threading.RLock()

def function_a():
    with lock:
        function_b()

def function_b():
    with lock:
        print("执行 function_b")

After function_a() acquires the lock, it calls function_b(), which acquires the same lock again.

With an ordinary non-reentrant mutex, the current thread may deadlock because it repeatedly requests a lock it already holds.

A reentrant lock typically records:

  • The thread currently holding the lock.
  • The lock's reentry count.

Each repeated acquisition increments the count by one; each release decrements it by one. The lock is actually released only when the count reaches zero.

Note: Reentrancy does not mean thread safety, nor does it mean locks can be nested arbitrarily. It only changes the behavior when the same thread repeatedly acquires the same lock.

2. Read-Write Lock

A read-write lock divides access operations into reads and writes.

Basic rules:

  • Multiple threads can hold the read lock simultaneously.
  • The write lock is usually exclusive.
  • While a writer thread holds the write lock, other reader and writer threads cannot access the protected region at the same time.

For example:

Thread A: Read configuration
Thread B: Read configuration
Thread C: Read configuration

The three threads can read simultaneously.

Thread D: Modify configuration

After Thread D acquires the write lock, other read and write operations must wait.

Read-write locks are suitable for scenarios with many reads and few writes, such as:

  • Configuration data queries.
  • Cache reads.
  • Routing table access.
  • Shared metadata queries.

However, a read-write lock is not necessarily faster than a mutex.

If write operations are frequent, a read-write lock may increase scheduling and synchronization overhead. The reader-preference, writer-preference, and fairness policies of different implementations may also cause starvation.

3. Fair Lock

A fair lock usually allocates access opportunities according to the order in which threads request the lock.

For example:

Thread A requests first
Thread B requests later
Thread C requests last

Allocation order:
Thread A → Thread B → Thread C

Advantages:

  • Reduces the risk of some threads being unable to acquire the lock for a long time.
  • Helps control waiting time.

Disadvantages:

  • May increase scheduling and queue-management overhead.
  • Reduces lock throughput.
  • May not fully exploit CPU cache locality.

Fairness is a strategy of the lock implementation, not an inherent property of all mutexes.

4. Optimistic Lock

An optimistic lock does not always protect resources through exclusive locking; instead, it assumes conflicts are few.

A thread first reads the data, completes its computation, then attempts to commit the modification and checks whether the data still remains in the expected state.

If the data has changed in the meantime, it rereads the data and retries.

For example, the version-number mechanism in a database:

UPDATE account
SET balance = 900,
    version = version + 1
WHERE id = 1
  AND version = 5;

If the number of affected rows is 1, the version matches and the update succeeds.

If the number of affected rows is 0, another transaction may have already modified the data, so it needs to be reread and processed again.

Optimistic locking is often used for:

  • Database version control.
  • Concurrent updates to web APIs.
  • Modification of distributed business state.
  • Shared resources with a low probability of conflict.

Note that version-number updates in a database rely on database transactions and atomic conditional updates, and are not equivalent to the CPU atomic instruction CAS.

5. Pessimistic Lock

A pessimistic lock assumes concurrent conflicts are relatively likely, so it acquires exclusive access before operating on the resource.

For example:

BEGIN;

SELECT balance
FROM account
WHERE id = 1
FOR UPDATE;

UPDATE account
SET balance = balance - 100
WHERE id = 1;

COMMIT;

The specific locking scope and behavior depend on the database, isolation level, indexes, and execution plan.

Pessimistic locking is suitable for scenarios with a high probability of conflict and where the business requires strict control over concurrent modifications.

6. Applicable Scenarios for Different Locks

Lock Type Core Characteristics Typical Applications
Mutex Only one thread can enter the critical section at a time Modifying shared variables
Spinlock Busy-waits to acquire the lock Extremely short critical sections
Reentrant Lock The same thread can acquire it repeatedly Recursive calls, nested calls
Read-Write Lock Multiple readers share; writers are exclusive Read-heavy, write-light workloads
Fair Lock Allocated according to a certain fairness policy Focus on waiting fairness
Optimistic Lock Checks for conflicts before committing Low-conflict updates
Pessimistic Lock Acquires exclusive permission before the operation High-contention workloads

7. Besides Locks, What Other Synchronization Mechanisms Are There?

Locks are an important means of thread synchronization, but they are not the only way.

In real-world engineering, atomic variables, semaphores, condition variables, barriers, and thread-safe queues are also often used.

1. Atomic Operations

An atomic operation is one whose intermediate state cannot be observed by other threads during execution.

For example:

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

atomic_int counter = 0;

void* increment(void* arg) {
    for (int i = 0; i < 100000; i++) {
        atomic_fetch_add(&counter, 1);
    }

    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);

    printf("counter = %d\n", atomic_load(&counter));

    return 0;
}

Here, atomic_fetch_add() is used to atomically increment the counter.

Multiple threads can safely perform this operation, and there is no need to use a mutex to protect this simple counter.

Atomic operations are commonly used for:

  • Counters.
  • State flags.
  • Reference counting.
  • Lock-free data structures.
  • Task status updates.

However, atomic operations do not mean that arbitrary multi-step business logic is atomic.

For example:

if (balance >= 100) {
    balance -= 100;
}

Even if an atomic variable is used for individual reads and writes of balance, it does not automatically guarantee that the entire check-and-deduct process is indivisible.

2. Semaphores

A semaphore is a synchronization mechanism that uses a counter to control the number of concurrent accesses to a resource.

It usually includes two core operations:

  • wait(): Requests a resource and decrements the count; waits if no resource is available.
  • signal(): Releases a resource and increments the count.

Suppose the system has 3 database connections:

import threading
import time

semaphore = threading.Semaphore(3)

def access_database():
    with semaphore:
        print("获得数据库连接")
        time.sleep(1)
        print("释放数据库连接")

Multiple threads can run concurrently, but at most 3 threads can enter the semaphore-limited region at any one time.

Semaphores are suitable for:

  • Database connection pools.
  • API concurrency rate limiting.
  • Thread pool task count control.
  • Managing a limited number of devices or resources.

Differences between semaphores and mutexes:

Comparison Dimension Mutex Semaphore
Primary Purpose Protect critical sections Control resource count or coordinate threads
State Usually indicates whether the lock is held Maintains a counter value
Allowed Concurrency Count Usually 1 Can be greater than 1
Ownership Usually has a lock-holding thread Does not usually require the releaser to be the acquirer

3. Condition Variables

A condition variable is used to make a thread wait until a certain condition becomes true.

It is usually used together with a mutex.

For example, the producer-consumer problem:

  • Producers are responsible for adding tasks to the queue.
  • Consumers are responsible for taking tasks from the queue.
  • When the queue is empty, consumers wait.
  • When there is data in the queue, consumers are woken up.

Python example:

import threading
from collections import deque

queue = deque()
condition = threading.Condition()

def producer():
    with condition:
        queue.append("task")
        condition.notify()

def consumer():
    with condition:
        while not queue:
            condition.wait()

        task = queue.popleft()
        print("处理任务:", task)

The key here is:

while not queue:
    condition.wait()

Why use while instead of if?

Because condition variables allow spurious wakeups, and after a thread is awakened, other threads may have already changed the shared state.

Therefore, after a thread is awakened, it must re-check the condition.

wait() usually releases the associated lock while waiting and reacquires it before returning.

4. Barrier

A barrier is used to coordinate multiple threads so that they continue executing only after reaching a specified synchronization point.

For example, if 4 threads each perform a computation, they must wait until all threads have completed the first phase before entering the second phase.

import threading
import time

barrier = threading.Barrier(4)

def worker(index):
    print(f"线程 {index} 完成第一阶段")

    barrier.wait()

    print(f"线程 {index} 开始第二阶段")

threads = [
    threading.Thread(target=worker, args=(i,))
    for i in range(4)
]

for thread in threads:
    thread.start()

for thread in threads:
    thread.join()

Barriers are commonly used in:

  • Parallel computing.
  • Scientific computing.
  • Multi-stage data processing.
  • Multithreaded simulation.
  • Synchronization testing.

5. Thread-Safe Queue

A thread-safe queue protects enqueue and dequeue operations through internal synchronization mechanisms.

For example, in Python:

import queue
import threading

task_queue = queue.Queue()

def producer():
    for i in range(10):
        task_queue.put(i)

def consumer():
    while True:
        item = task_queue.get()

        try:
            print("处理任务:", item)
        finally:
            task_queue.task_done()

threading.Thread(target=producer).start()
threading.Thread(target=consumer, daemon=True).start()

In real-world engineering, a thread-safe queue is usually more reliable than implementing a producer-consumer model yourself using lists and locks.

It can encapsulate:

  • Enqueue and dequeue synchronization.
  • Queue capacity limits.
  • Blocking waits.
  • Task completion notifications.

Note that the consumer in this example is a daemon thread, demonstrating the basic consumption process; a production environment should also design explicit exit signals, exception handling, and thread cleanup mechanisms.

8. Memory Visibility: Why Is Locking Not Just for Mutual Exclusion?

Thread safety has another important issue: memory visibility.

Even if two threads do not modify the same variable at the same time, due to factors such as caching, compiler optimization, and CPU instruction reordering, they may fail to observe each other's modifications as expected.

1. What Is Memory Visibility?

Suppose:

class Worker {
    boolean running = true;

    void stop() {
        running = false;
    }

    void work() {
        while (running) {
            // Execute the task
        }
    }
}

One thread executes work(), and another thread executes stop().

The programmer expects:

Thread A: running = true
Thread B: running = false
Thread A: observes false and exits the loop

However, without appropriate synchronization, the Java Memory Model does not guarantee that Thread A will observe Thread B's modification in a timely manner.

In Java, you can use volatile:

class Worker {
    volatile boolean running = true;

    void stop() {
        running = false;
    }

    void work() {
        while (running) {
            // Execute the task
        }
    }
}

volatile can provide certain visibility and ordering guarantees.

But it cannot guarantee the atomicity of compound operations.

For example:

volatile int counter = 0;

counter++;

counter++ is still not an atomic operation.

When multiple threads execute it concurrently, lost updates can still occur.

2. The happens-before Relationship

happens-before is a core concept in the concurrency memory model; it defines which operations between different threads have visibility and ordering guarantees.

It is not a simple physical chronological relationship, but a partial order relation specified by a language memory model.

In Java, common happens-before rules include:

  • Within the same thread, earlier operations happen-before later operations.
  • A write to a volatile variable happens-before a subsequent read of that variable.
  • Unlocking a monitor happens-before a subsequent lock of the same monitor.
  • Operations before Thread.start() happen-before operations in the started thread.
  • Operations in a thread happen-before operations in other threads that successfully detect that thread's termination.

For example:

class SharedData {
    int value = 0;
    boolean ready = false;
}

SharedData data = new SharedData();

Thread A:

data.value = 100;
data.ready = true;

Thread B:

if (data.ready) {
    System.out.println(data.value);
}

If ready is an ordinary variable, then in the absence of a synchronization relationship, there is no guarantee that Thread B will observe value = 100.

If ready is declared volatile:

volatile boolean ready = false;

then a happens-before relationship is established between Thread A's write to ready and Thread B's subsequent read that observes that write.

Therefore, when Thread B observes ready == true, it can also see value = 100, which Thread A completed before that volatile write.

3. How Do Locks Establish Memory Visibility?

In Java, an unlock operation on a given monitor lock happens-before a subsequent lock operation on that same lock by another thread.

This means:

synchronized (lock) {
    sharedData = 100;
}

Another thread executes:

synchronized (lock) {
    System.out.println(sharedData);
}

If the second thread successfully acquires the same monitor lock, it can see the relevant writes completed by the first thread before releasing the lock.

Thus, locks not only provide mutual exclusion but also establish a memory synchronization relationship between threads.

4. How Memory Visibility Works

flowchart TD
    A["Thread A modifies shared data"] --> B["Thread A performs a synchronization operation"]
    B --> C["Establishes a memory synchronization relationship"]
    C --> D["Thread A releases the lock or publishes state"]
    D --> E["Thread B acquires the same lock or observes the synchronization state"]
    E --> F["Thread B reads shared data"]
    F --> G["Observes the modification guaranteed by the synchronization relationship"]

    style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
    style B fill:#DCEFE5,stroke:#8EBFA5,color:#24563F
    style C fill:#EDE7F8,stroke:#B9A4DC,color:#514174
    style D fill:#DCEFE5,stroke:#8EBFA5,color:#24563F
    style E fill:#DCEFE5,stroke:#8EBFA5,color:#24563F
    style F fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
    style G fill:#FFF3D6,stroke:#E7C77D,color:#75551D

Memory models differ across languages. Java's volatile, C++'s std::atomic, and Go's synchronization primitives each have their own rules; you cannot simply apply one language's guarantees directly to another language.

IX. Deadlock: What Problems Can Improper Lock Usage Cause?

Locks can protect shared resources, but if used incorrectly, they can also lead to deadlock.

A deadlock occurs when multiple threads cannot continue executing because each is waiting for a resource held by another.

1. Deadlock Example

Suppose there are two locks:

import threading

lock_a = threading.Lock()
lock_b = threading.Lock()

def thread_a():
    with lock_a:
        print("线程 A 获得 lock_a")

        with lock_b:
            print("线程 A 获得 lock_b")

def thread_b():
    with lock_b:
        print("线程 B 获得 lock_b")

        with lock_a:
            print("线程 B 获得 lock_a")

Possible output:

Thread A acquired lock_a
Thread B acquired lock_b

Thread A waiting for lock_b
Thread B waiting for lock_a

Thread A holds lock_a and waits for lock_b.

Thread B holds lock_b and waits for lock_a.

Neither can proceed.

2. Four Necessary Conditions for Deadlock

Classic deadlock theory includes four necessary conditions:

Mutual Exclusion

A resource can be occupied by only one thread at a time.

Request and Hold

A thread already holds some resources and continues to request other resources.

No Preemption

Resources held by a thread cannot be forcibly taken away; they can only be released voluntarily by the holder.

Circular Wait

Multiple threads form a circular resource-waiting relationship.

When these four conditions hold simultaneously, the system may deadlock.

3. How Deadlock Forms

flowchart TD
    A["Thread A acquires Lock A"] --> B["Thread B acquires Lock B"]
    B --> C["Thread A requests Lock B"]
    C --> D["Thread A waits for Thread B"]
    D --> E["Thread B requests Lock A"]
    E --> F["Thread B waits for Thread A"]
    F --> G["Circular wait forms"]
    G --> H["System deadlocks"]

    style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
    style B fill:#DCEFE5,stroke:#8EBFA5,color:#24563F
    style C fill:#FFF3D6,stroke:#E7C77D,color:#75551D
    style D fill:#FCE7E7,stroke:#E5A3A3,color:#8A3636
    style E fill:#FFF3D6,stroke:#E7C77D,color:#75551D
    style F fill:#FCE7E7,stroke:#E5A3A3,color:#8A3636
    style G fill:#FCE7E7,stroke:#E5A3A3,color:#8A3636
    style H fill:#FCE7E7,stroke:#E5A3A3,color:#8A3636