OSTEP - Notes on the Concurrency Section
Last updated on June 27, 2026 am
This article is currently an experimental machine translation and may contain errors. If anything is unclear, please refer to original Chinese version. I am continuously working to improve the translation.
Chapter 26 Concurrency: An Introduction
Threads
def: A thread is a single execution flow within a process.
In a multi-threaded process, there are multiple execution flows within one process:
- Each thread has its own PC and other registers, and its own stack, used to save context
- All threads share one address space
- The scheduler switches between different threads
- The OS uses a TCB (Thread Control Block) to manage thread state
- The so-called shared data refers to data in memory; for a thread, register data is not shared — each thread has its own set of registers
Reasons for Using Threads
- Parallelism
- CPUs are multi-core, so a large task can be split into several parts and handled by multiple threads simultaneously
- Avoiding slow operations blocking the program
- For example, disk I/O, network, page faults — during these, other threads can continue running
- The advantage of threads lies in the convenience of sharing data.
Problems with Concurrency
-
Once a thread is created, when it runs is decided by the scheduler, not entirely by the order in which the code is written.
For example:
static volatile int counter = 0; void *mythread(void *arg) { for (int i = 0; i < 1e7; i++) { counter = counter + 1; } return NULL; }After running, the result might look like this:
counter = 19345221 counter = 19221041This is because
counter = counter + 1;corresponds to the following assembly:mov 0x8049a1c, %eax add $0x1, %eax mov %eax, 0x8049a1cThread switches, can happen between these three assembly instructions.
-
Thread waiting: sometimes a thread must wait for another thread to finish before it can continue running, i.e., the wait/wake-up problem.
Summary of Key Terms
- critical section: a code segment that accesses a shared resource and should not be executed by multiple threads simultaneously; for example, in the code above, the critical section is
counter = counter + 1; - indeterminate program: literally what it says
- race condition: refers to a program's result depending on the timing of thread execution (determined by scheduling order)
- mutual exclusion: the property we want: when one thread is inside a critical section, other threads cannot enter the same critical section
Atomicity
def: An operation is a whole, indivisible.
For example, we would like the three assembly instructions above to execute as if there were one indivisible memory-add 0x8049a1c, $0x1 instruction.
But in reality, we cannot provide atomic operations for all complex operations, so we need the OS and thread libraries to build general-purpose data primitives on top of them, such as locks, to achieve the goal of synchronizing shared data and mutual exclusion of critical sections.
Chapter 27 Thread API
Introducing a few basic APIs provided by the POSIX thread library pthread:
Creating Threads with pthread_create()
int pthread_create(pthread_t *thread,
const pthread_attr_t *attr,
void *(*start_routine)(void *),
void *arg);
thread: used to store the identifier of the new thread; later you can use it tojointhis thread.attr: thread attributes, such as stack size and scheduling attributes; usually passNULL, meaning default attributes.start_routine: the function from which the new thread starts executing.arg: the argument passed to this thread function.
The thread start function must look like this:
void *mythread(void *arg) {
}If you need to pass multiple arguments, you can pack them into a struct and pass that.
Once a thread is created, it becomes a new execution flow with its own call stack, and shares the same address space as the original thread.
Waiting for a Thread to Finish with pthread_join()
int pthread_join(pthread_t thread, void **value_ptr);-
threadis the thread whose completion we are waiting for -
value_ptris the expected return valueWhy is the parameter here
void**? Because the thread function's return value isvoid*.
For example:
void *mythread(void *arg) {
myret_t *rvals = malloc(sizeof(myret_t));
rvals->x = 1;
rvals->y = 2;
return rvals;
}
int main() {
pthread_t p;
pthread_create(&p, NULL, mythread, &args);
myret_t *rvals;
pthread_join(p, (void **) &rvals);
}A thread's return value must be placed on the heap; if you return the address of a local variable on the stack, it will be destroyed after the function ends.
Mutex Locks
int pthread_mutex_lock(pthread_mutex_t *mutex);
int pthread_mutex_unlock(pthread_mutex_t *mutex);Typical usage:
pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
// 或者
// pthread_mutex_t lock;
// pthread_mutex_init(&lock, NULL);
pthread_mutex_lock(&lock);
x = x + 1;
pthread_mutex_unlock(&lock);- If no other thread holds the lock, the current thread acquires the lock and enters the critical section.
- If another thread already holds the lock, the current thread will block in
pthread_mutex_lock()until the lock is released. - Only the thread that acquired the lock should call
pthread_mutex_unlock(). - If the lock is no longer used after the program ends, you can also call
pthread_mutex_destroy()to clean it up.
These APIs all have return values; a return value of 0 means success. The code above should check them, but it was omitted for brevity.
Condition Variables
int pthread_cond_wait(pthread_cond_t *cond,
pthread_mutex_t *mutex);
int pthread_cond_signal(pthread_cond_t *cond);- The former is for sleeping, the latter for waking up
- Condition variables are always used together with locks: a thread releases the lock when it sleeps and reacquires the lock when it wakes up
Principles for Using the Thread API
- Keep interactions between threads as simple as possible
- Locks and condition variables must be initialized
- All calls must check return values
- Don't return values that live on the stack
- Each thread has its own stack; to share data, place it on the heap or in a globally accessible location
Chapter 28 Locks
The Basic Idea of Locks
A lock's state: locked and unlocked
It is essentially a means of scheduling processes given to the programmer.
Criteria for Evaluating Locks
- Correctness: it truly provides mutual exclusion, allowing only one thread into the critical section
- Fairness: preventing a thread from never acquiring the lock, leading to starvation
- Performance: the overhead of the lock itself:
- Efficiency of acquiring/releasing the lock when there is no contention
- Efficiency under single-CPU multi-thread contention and multi-CPU multi-thread contention
Next, we will list a series of lock implementations.
Controlling Interrupts
void lock() {
DisableInterrupts();
}
void unlock() {
EnableInterrupts();
}Drawbacks:
- Requires user programs to be able to execute privileged operations, which is dangerous
- Does not support multiple CPUs, because threads on other CPUs don't have interrupts disabled
- Disabling interrupts makes I/O impossible (recall that I/O and similar operations require a trap into kernel mode via interrupts)
test-and-set
void lock(lock_t *mutex) {
while (mutex->flag == 1)
; // spin
mutex->flag = 1;
}
void unlock(lock_t *mutex) {
mutex->flag = 0;
}Intuitively, this code will fail, because checking flag and setting flag is not an atomic operation.
When implementing a lock, you must not split "checking whether the lock is free" and "setting the lock as occupied" into two interruptible steps.
So we need to rely on hardware support. Suppose there is such an atomic operation (the C code here is just for ease of understanding; in reality it is atomic):
int TestAndSet(int *old_ptr, int new) {
int old = *old_ptr;
*old_ptr = new;
return old;
}Then we can implement a simple spin lock:
void lock(lock_t *lock) {
while (TestAndSet(&lock->flag, 1) == 1)
; // spin
}
void unlock(lock_t *lock) {
lock->flag = 0;
}Problems with spin locks:
- No guarantee of fairness, which may lead to starvation;
- Poor performance: other threads that fail to acquire the lock keep spinning, wasting time slices.
Other Hardware Primitives
Compare and Swap
int CompareAndSwap(int *ptr, int expected, int new) {
int original = *ptr;
if (original == expected)
*ptr = new;
return original;
}
void lock(lock_t *lock) {
while (CompareAndSwap(&lock->flag, 0, 1) == 1)
; // spin
}Load-Linked / Store-Conditional
First LoadLinked() reads a value, then StoreConditional() attempts to write; if no one has modified that address in between, the write succeeds, otherwise it fails.
Fetch-and-Add
代码
int FetchAndAdd(int *ptr) {
int old = *ptr;
*ptr = old + 1;
return old;
}
typedef struct lock_t {
int ticket = 0;
int turn = 0;
} lock_t;
void lock(lock_t *lock) {
int myTurn = FetchAndAdd(&lock->ticket);
while(lock->turn != myTurn)
; //spin
}
void unlock(lock_t *lock) {
lock->turn = lock->turn + 1;
}ticket: the number the next person in line should get;turn: whose turn it is now to enter the critical section.
Only when turn == myTurn is a thread allowed to enter the critical section; after release, it's the next thread's turn.
This solves the starvation problem, but not the spin lock's performance problem.
Solving the Problem of Excessive Spinning
A simple improvement is to yield() when the lock cannot be acquired: the current thread voluntarily gives up the CPU and returns to the ready queue, letting others run.
void lock(lock_t *lock) {
while(TestAndSet(&flag, 1) == 1) {
yield();
}
}Problem: when multiple threads repeatedly contend for the same lock, there is a large cost of context switches.
Another improvement: make threads waiting for the lock sleep.
Here we use two Solaris APIs as an example:
park(): puts the current thread to sleep;unpark(threadID): wakes up the specified thread.
typedef struct lock_t {
int flag;
int guard;
queue_t *q;
} lock_t;flag: whether the actual lock is held;guard: a small spin lock protecting the lock's internal data structures;q: the queue of threads waiting for this lock.
Then:
-
When a thread cannot acquire the lock, it adds itself to the queue and sleeps via
park();void lock(lock_t *lock) { while(TestAndSet(&lock->guard, 1) == 1) ; if (lock->flag == 0) { lock->flag = 1; lock->guard = 0; } else { queue_add(lock->q); lock->guard = 0; park(); } } -
When releasing the lock, if the queue is non-empty,
unpark()wakes up the next sleeping process.
Possible problem:
- Thread A has just added itself to the queue
- Context switches to thread B; thread B releases the lock and calls
unpark(A) - As a result, when switching back to A, A calls
parkagain and keeps sleeping
This can be solved by designing other OS primitives.
Two-Phase Locks
- Phase one: spin for a short while first (a fixed number of times), hoping the lock will be released soon;
- Phase two: if the lock still cannot be acquired, sleep and wait to be woken up.
This is also a hybrid approach, adopted by the Linux Kernel.
Chapter 29 Concurrent Data Structures with Locks
As the title suggests, this chapter discusses the design of concurrent data structures and the trade-offs involved.
The simplest approach: directly add a single lock around the entire data structure's CRUD operations, but this may lead to performance deficiencies (all threads contend for the same lock).
So it may be necessary to split the lock more finely, but finer is not always better.
Concurrent Counter
Add a lock to the counter:
typedef struct counter_t {
int value;
pthread_mutex_t lock;
} counter_t;
void increment(counter_t *c) {
pthread_mutex_lock(&c->lock);
c->value++;
pthread_mutex_unlock(&c->lock);
}Correct, but with a drawback: all threads contend for the same lock, and the more frequent the updates, the more severe the contention.
Approximate Counter
This is just an idea.
typedef struct __counter_t {
int global;
pthread_mutex_t glock;
int local[NUMCPUS];
pthread_mutex_t llock[NUMCPUS];
int threshold;
} counter_t;- There is a global counter
globalwith a global lockglock, used only when updating the global counter; - There is a series of local counters
local[i]and local locksllock[i], locked when updating local counters
Update logic:
void increment(counter_t *c, int cpu, int amt) {
pthread_mutex_lock(&c->llock[cpu]);
c->local[cpu] += amt;
if (c->local[cpu] >= c->threshold) {
pthread_mutex_lock(&c->glock);
c->global += c->local[cpu];
pthread_mutex_unlock(&c->glock);
c->local[cpu] = 0;
}
pthread_mutex_unlock(&c->llock[cpu]);
}That is:
- First lock the local counter;
amtis the increment per update, andcpucan be understood as the thread's ID - If the local counter's value exceeds the threshold
threshold, update the global counter, which also requires locking - The resulting global counter is approximate
Trade-offs:
- With this design, all threads no longer constantly contend for the same lock
- But the resulting value is imprecise
- The choice of threshold also involves trade-offs:
- A large threshold gives better performance, but the global counter may lag behind
- A small threshold is the opposite
Concurrent Linked List
The simplest concurrent linked list: use one big lock:
typedef struct __list_t {
node_t *head;
pthread_mutex_t lock;
} list_t;Insertion:
void insert(list_t *l, int key) {
node_t *new = malloc(sizeof(node_t));
if (new == NULL) {
return -1;
}
new->key = key;
pthread_mutex_lock(&l->lock);
new->next = l->head;
l->head = new;
pthread_mutex_unlock(&l->lock);
}Note the concurrent coding style here: we only lock the critical section that modifies the entire linked list, while extracting the earlier part out; the lock is only taken when actually modifying the shared list.
Hand-over-hand Locking
This example mainly demonstrates that splitting locks too finely is also bad.
Suppose instead of locking the linked list's list_t struct, we lock the node_t struct, i.e., each node of the list has a lock:
- Intuitively this could increase concurrency, but in practice the overhead of lock / unlock far exceeds the benefit brought by concurrency
Finer locks ≠ better performance
Concurrent Queue
Demonstrating "reasonable lock splitting"
typedef struct __queue_t {
node_t *head;
node_t *tail;
pthread_mutex_t head_lock, tail_lock;
} queue_t;- Enqueue only needs to touch the head pointer, dequeue only needs to touch the tail pointer
- So splitting the locks this way is very efficient
Concurrent Hash Table
Reusing the concurrent linked list:
#define BUCKETS (101)
typedef struct __hash_t {
list_t lists[BUCKETS];
} hash_t;CRUD operations only touch a particular bucket:
int Hash_Insert(hash_t *H, int key) {
return List_Insert(&H->lists[key % BUCKETS], key);
}
int Hash_Lookup(hash_t *H, int key) {
return List_Lookup(&H->lists[key % BUCKETS], key);
}Good performance, because different keys fall into different buckets; the buckets are independent of each other, so lock contention is unlikely.
Summary
- more concurrency isn't necessarily faster;
- avoid premature optimization
Chapter 30 Condition Variables
Recall what was said before: the two problems of concurrency are the need for mutual exclusion and the need for a wait/wake-up mechanism. Condition variables solve the wait/wake-up mechanism.
The Problem Condition Variables Solve
Suppose we have a scenario where a parent thread needs to wait for a child thread to finish:
parent: begin;
child: operates;
parent: end;We can use a shared variable to solve this problem:
volatile int done = 0;
void *child(void *arg) {
printf("child\n");
done = 1;
return NULL;
}
int main() {
pthread_t c;
printf("parent: begin\n");
Pthread_create(&c, NULL, child, NULL);
while (done == 0)
; // spin
printf("parent: end\n");
}Problem: the parent thread keeps spinning, occupying the CPU.
Therefore, a sleep/wake-up mechanism is introduced: when a thread needs some condition to hold, it sleeps instead of spinning, until it is woken up.
Condition Variables
def: A condition variable is a set of waiters.
- When a thread finds that the condition it needs does not yet hold, it:
- Adds itself to the wait set of that condition variable
- Sleeps
- Later, another thread changes the state so that the condition is satisfied, and then:
- Sends a signal on that condition variable, waking up one waiting thread
Using POSIX as an example, the sleep and wake-up APIs are:
int pthread_cond_wait(pthread_cond_t *cond,
pthread_mutex_t *mutex);
int pthread_cond_signal(pthread_cond_t *cond);They actually have return values, but we won't check them in what follows.
wait: the condition doesn't hold, release the lock and sleep (this operation is atomic)signal: the state has changed, wake up and take a look (does not mean continue, explained later)
Why Condition Variables Must Be Used with Locks
First, one thing must be made clear: the condition variable itself does not represent the condition; shared variables / state variables represent the condition.
Here is a piece of correct code:
int done = 0;
pthread_mutex_t m = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t c = PTHREAD_COND_INITIALIZER;
void thr_exit() {
Pthread_mutex_lock(&m);
done = 1;
Pthread_cond_signal(&c);
Pthread_mutex_unlock(&m);
}
void thr_join() {
Pthread_mutex_lock(&m);
while (done == 0)
Pthread_cond_wait(&c, &m);
Pthread_mutex_unlock(&m);
}If no lock is taken in thr_join(), then:
done == 0holds, and the thread is about towait;- But at this moment it gets switched out (note this is caused by not taking the lock);
- The child thread runs, sets
done == 1, and sends asignal; - But at this point, since no thread is waiting on
cond_t c, it's as if nothing was sent; - Then it switches back to the parent thread, which directly calls
waitand goes to sleep; - It can never wake up again, because it can never be
signaled.
Moreover, wait also takes a lock as a parameter (recall the role of wait), so using a lock is mandatory.
The Producer - Consumer Problem
Problem Background
Suppose there is a shared buffer that can hold only one integer at a time; here we can simply write it as int count, taking the value 0 or 1:
- The producer thread is responsible for
putting a value into it, and can onlyputwhen the buffer is not full; - The consumer thread is responsible for
getting a value from it, and can onlygetwhen the buffer is not empty.
That is, using this simplified model as an example:
- The producer needs to wait for the condition
count == 0; - The consumer needs to wait for the condition
count == 1.
Condition variables are needed.
Why Use while Instead of if
In short, being woken up does not mean the condition still holds; using while allows the condition to be rechecked each time the thread wakes up.
One Condition Variable May Not Be Enough
while (count == 1)
wait(cond, mutex); // producer
while (count == 0)
wait(cond, mutex); // consumerSuch code may have bugs, because producers and consumers wait on the same cond, and the wake-up order can be problematic.
So, different wait queues should use different condition variables:
代码
cond_t empty, fill;
mutex_t mutex;
void *producer(void *arg) {
for (...) {
Pthread_mutex_lock(&mutex);
while (count == 1)
Pthread_cond_wait(&empty, &mutex);
put(i);
Pthread_cond_signal(&fill);
Pthread_mutex_unlock(&mutex);
}
}
void *consumer(void *arg) {
for (...) {
Pthread_mutex_lock(&mutex);
while (count == 0)
Pthread_cond_wait(&fill, &mutex);
int tmp = get();
Pthread_cond_signal(&empty);
Pthread_mutex_unlock(&mutex);
printf("%d\n", tmp);
}
}- The producer waits for an empty slot and sleeps on
empty, and vice versa.
Chapter 31 Semaphores
def: A synchronization object with an integer value, representing "how many resources are currently available".
- When
S.value > 0, it represents the number of resources that can be allocated immediately; - When
S.value = 0, it means no resources are available; - When
S.value < 0, its absolute value represents the number of threads/processes waiting on that semaphore.
Two core operations:
sem_wait(&s): decrements the semaphore by one; if the semaphore becomes negative after the decrement, sleep and wait;sem_post(&s): increments the semaphore by one; if the semaphore is still non-positive afterwards, wake up one waiting thread.
Setting the semaphore's initial value is very important.
Semaphores as Mutex Locks - Binary Semaphores
sem_t m;
sem_init(&m, 0, 1);
sem_wait(&m);
// critical section
sem_post(&m);Why is the initial value 1? Because the lock is initially free, allowing the first thread to directly take this one permit.
If thread A executes sem_wait() first:
- The semaphore goes from
1to0 - A does not block and enters the critical section
If thread B also executes sem_wait() at this point:
- The semaphore goes from
0to-1 - B sees a negative value and sleeps waiting
When A executes sem_post():
- The semaphore goes from
-1to0 - B is woken up
Semaphores as Condition Variables - Ordering Control
The semaphore's initial value is 0.
sem_t s;
void *child(void *arg) {
printf("child\n");
sem_post(&s);
return NULL;
}
int main() {
sem_init(&s, 0, 1);
printf("parent: begin\n");
Pthread_create(&c, NULL, child, NULL);
sem_wait(&s);
printf("parent: end\n");
}Why is the initial value 0 here?
Because at the start, the child thread hasn't finished yet, so the parent thread has no "completion signal" to take.
There are two possible execution orders:
- The parent thread calls
sem_wait()first: the semaphore becomes negative, and the parent thread sleeps; after the child thread finishes,sem_post()wakes the parent thread. - The child thread calls
sem_post()first: the semaphore becomes1; when the parent thread later callssem_wait(), it passes directly.
Semaphores as Condition Variables - The Producer-Consumer Problem
int buffer[MAX]; // 共享缓冲区有 MAX 个槽位
int fill = 0; // use = MAX - 1 - fill,理解为可用的- The producer needs to wait for
useto differ from0 - The consumer needs to wait for
fillto differ from0
Our final solution:
代码
sem_t empty; // 空槽数量
sem_t full; // 已填充槽数量
sem_t mutex;
sem_init(&empty, 0, MAX);
sem_init(&full, 0, 0);
sem_init(&mutex, 0, 1);
// 生产者
sem_wait(&empty);
sem_wait(&mutex);
put(i);
sem_post(&mutex);
sem_post(&full);
// 消费者
sem_wait(&full);
sem_wait(&mutex);
tmp = get();
sem_post(&mutex);
sem_post(&empty);- Without
mutexas a mutual exclusion lock, since theputoperation is not atomic (updatingbufferand updatingfillis not atomic in between). Suppose there are two producers; the valueputby the former might be overwritten by the valueputby the latter. - If
sem_wait(&empty); sem_wait(&mutex);are swapped, the thread would first acquire themutexlock and then fall asleep, leading to deadlock.
Reader - Writer Locks
For a data structure, we need:
- Multiple readers can enter simultaneously
- Writers must have exclusive access
- Readers and writers cannot enter simultaneously
Implementation:
代码
typedef struct __rwlock_t {
sem_t lock;
sem_t writelock;
int readers;
} rwlock_t;
void rwlock_init(rwlock_t *lock) {
lock->readers = 0;
Sem_init(&lock->lock, 1);
Sem_init(&lock->writelock, 1);
}
void rwlock_acquire_readlock(rwlock_t *lock) {
Sem_wait(&lock->lock);
lock->readers++;
if (lock->readers == 1)
Sem_wait(&lock->writelock);
Sem_post(&lock->lock);
}
void rwlock_release_readlock(rwlock_t *lock) {
Sem_wait(&lock->lock);
lock->readers--;
if (lock->readers == 0)
Sem_post(&lock->writelock);
Sem_post(&lock->lock);
}
void rwlock_acquire_writelock(rwlock_t *lock) {
Sem_wait(&lock->writelock);
}
void rwlock_release_writelock(rwlock_t *lock) {
Sem_post(&lock->writelock);
}In short:
- The first reader holds
writelock, preventing writers from entering; - Subsequent readers can enter directly (because each reader releases
lockafter reading, but the first reader does not releasewritelock) - The last reader releases
writelock, allowing writers to enter
But there is a fairness problem: if readers keep streaming in, writers will starve.
Solution: set an upper limit on the readers value.
The Dining Philosophers Problem
Five people sit around a table, with a fork between each pair of adjacent people. Each person needs the two forks on their left and right to eat. Goal: how to implement the getforks() and putforks() functions to guarantee no deadlock, no starvation, and maximum concurrency.
sem_t forks[5];
int left(p) {return p;}
int right(p) {return (p + 1) % 5;}
void getforks() {
sem_wait(forks[left(p)]);
sem_wait(forks[right(p)]);
}
void putforks() {
sem_post(forks[left(p)]);
sem_post(forks[right(p)]);
}This solution has a problem: deadlock: everyone has picked up the left fork but is all waiting for the right one, and they deadlock like this forever.
Solution: for one particular person, have them pick up the right fork first, then the left.
Limiting Concurrency
sem_t throttle;
sem_init(&throttle, 0, 10);
...
sem_wait(&throttle);
... code
sem_post(&throttle);This limits at most 10 threads to running this code simultaneously.
How to Implement a Semaphore
typedef struct {
int value;
pthread_cond_t cond;
pthread_mutex_t lock;
} Zem_t;wait:
Mutex_lock(&s->lock);
while (s->value <= 0)
Cond_wait(&s->cond, &s->lock);
s->value--;
Mutex_unlock(&s->lock);post:
Mutex_lock(&s->lock);
s->value++;
Cond_signal(&s->cond);
Mutex_unlock(&s->lock);Chapter 32 Common Concurrency Bugs
Non-Deadlock Bugs
Atomicity Violation
A MySQL example:
// Thread 1
if (thd->proc_info) {
fputs(thd->proc_info, ...);
}
// Thread 2
thd->proc_info = NULL;For Thread 1, at this moment it checks that thd->proc_info is non-null, but the next moment it is switched out to Thread 2, which sets thd->proc_info to null; afterwards, a serious bug will obviously occur.
Solution: add a lock
// thread 1
pthread_mutex_lock(&proc_info_lock);
if (thd->proc_info) {
fputs(thd->proc_info, ...);
}
pthread_mutex_unlock(&proc_info_lock);
// thread 2
pthread_mutex_lock(&proc_info_lock);
thd->proc_info = NULL;
pthread_mutex_unlock(&proc_info_lock);Order Violation
Just use appropriate condition variables to enforce the ordering.
Deadlock Bugs
For example:
// Thread 1
pthread_mutex_lock(L1);
pthread_mutex_lock(L2);
// Thread 2
pthread_mutex_lock(L2);
pthread_mutex_lock(L1);If Thread 1 acquires L1 first and Thread 2 acquires L2 first, it becomes:
- Thread 1 holds
L1, waiting forL2 - Thread 2 holds
L2, waiting forL1
This forms a deadlock.
Conditions for Deadlock
All four conditions must hold simultaneously:
- Mutual exclusion: resources are mutually exclusive, e.g., a lock can only be held by one thread at a time.
- Hold-and-wait: a thread holds one resource while waiting for another.
- No preemption: resources cannot be forcibly taken from their holder, e.g., a lock can only be released by its holder.
- Circular wait: multiple threads form a circular waiting chain.
As long as any one of these conditions is broken, deadlock cannot occur.
How to Prevent Deadlock
Breaking circular wait
The main problem in forming a circular waiting chain is that the order of acquiring locks is not fixed; the solution is to fix the lock acquisition order for all threads, making a cycle impossible.
For example, all threads are required to acquire L1 first, then L2.
Breaking hold-and-wait
Use a global lock to make the "acquiring locks" process atomic:
pthread_mutex_lock(prevention);
pthread_mutex_lock(L1);
pthread_mutex_lock(L2);
pthread_mutex_unlock(prevention);Drawback: reduced concurrency.
trylock
If the second lock cannot be acquired, give up and retry:
top:
pthread_mutex_lock(L1);
if (pthread_mutex_trylock(L2) != 0) {
pthread_mutex_unlock(L1);
goto top;
}But livelock may occur: both threads keep yielding and retrying, but neither actually makes progress. It is not a hang, because the threads are still running; but there is no progress.
Avoiding mutual exclusion
That is, use hardware primitives to build atomic instructions, without locks.
Chapter 33 Event-Based Concurrency
The previous chapters said "concurrency = multi-threading + locks + semaphores + condition variables", but this is not the only approach.
In fact, the previous JavaScript Notes - the JavaScript Asynchrony section introduced this approach to implementing asynchrony in detail.
Basically: there is a while(1) event loop and a message queue (event queue), and the event loop keeps iterating over the event queue.
So we won't go into detail here.