Skip to content
Quantoros

Mutex, condition variable, and read-write lock — when is each appropriate?

C++Level: IntermediateConcurrency & OS

Mutex, condition variable, and read-write lock — when is each appropriate?

Hints
  • Separate concurrency from parallelism and identify shared state.
  • Consider locking, access ordering and I/O-bound versus CPU-bound work.

Answer

Mutex Synchronization

:Source: src/thread/mutex

A mutex (mutual exclusion lock) ensures that only one thread can execute a critical section at a time. When a thread calls pthread_mutex_lock(), it either acquires the lock immediately or blocks until the lock becomes available. The thread must call pthread_mutex_unlock() to release the lock, allowing other waiting threads to proceed.

Without mutex protection, concurrent access to shared variables causes race conditions. For example, incrementing a counter involves reading the current value, adding one, and writing back—three operations that can interleave unpredictably across threads. Mutexes serialize these operations, ensuring correct results at the cost of some performance overhead.

Initialize static mutexes with PTHREAD_MUTEX_INITIALIZER. For dynamically allocated mutexes, use pthread_mutex_init() and pthread_mutex_destroy(). Always pair lock and unlock calls, and consider using RAII patterns in C++ to prevent forgetting to unlock.

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

int counter = 0;
pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;

void *increment(void *arg) {
  for (int i = 0; i < 100000; i++) {
    pthread_mutex_lock(&lock);
    counter++;
    pthread_mutex_unlock(&lock);
  }
  return NULL;
}

int main(void) {
  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);  // always 200000
}
$ gcc -pthread -o mutex main.c && ./mutex
Counter: 200000

Answer section

Condition Variables

:Source: src/thread/condvar

Condition variables allow threads to block until a particular condition becomes true, enabling efficient producer-consumer patterns and other synchronization scenarios. Unlike busy-waiting (repeatedly checking a condition in a loop), condition variables put the thread to sleep until another thread signals that the condition may have changed.

The pthread_cond_wait() function atomically releases the associated mutex and blocks the calling thread. When the thread is awakened by a signal, it automatically reacquires the mutex before returning. This atomic release-and-wait prevents race conditions between checking the condition and going to sleep.

Always use a while loop to recheck the condition after pthread_cond_wait() returns, because spurious wakeups can occur and multiple threads may be competing for the same condition. Use pthread_cond_signal() to wake one waiting thread or pthread_cond_broadcast() to wake all waiters when the condition affects multiple threads.

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

int ready = 0;
pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;

void *producer(void *arg) {
  pthread_mutex_lock(&lock);
  ready = 1;
  pthread_cond_signal(&cond);
  pthread_mutex_unlock(&lock);
  return NULL;
}

void *consumer(void *arg) {
  pthread_mutex_lock(&lock);
  while (!ready)
    pthread_cond_wait(&cond, &lock);
  printf("Consumer: data ready\n");
  pthread_mutex_unlock(&lock);
  return NULL;
}

int main(void) {
  pthread_t prod, cons;
  pthread_create(&cons, NULL, consumer, NULL);
  pthread_create(&prod, NULL, producer, NULL);
  pthread_join(prod, NULL);
  pthread_join(cons, NULL);
}
$ gcc -pthread -o condvar main.c && ./condvar
Consumer: data ready

Answer section

Read-Write Locks

:Source: src/thread/rwlock

Read-write locks optimize access patterns where reads are frequent and writes are rare. Multiple threads can hold the read lock simultaneously, allowing concurrent read access to shared data. However, the write lock is exclusive—only one thread can hold it, and no readers are allowed while a writer has the lock.

Use pthread_rwlock_rdlock() for read access and pthread_rwlock_wrlock() for write access. This distinction improves throughput compared to a regular mutex when most operations are reads, as readers don't block each other. However, read-write locks have higher overhead than mutexes, so they're only beneficial when the read-to-write ratio is high and critical sections are long enough to amortize the locking cost.

Be aware of writer starvation: if readers continuously acquire the lock, writers may wait indefinitely. Some implementations provide fairness policies to prevent this, but behavior varies across platforms.

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

int data = 0;
pthread_rwlock_t rwlock = PTHREAD_RWLOCK_INITIALIZER;

void *reader(void *arg) {
  pthread_rwlock_rdlock(&rwlock);
  printf("Read: %d\n", data);
  pthread_rwlock_unlock(&rwlock);
  return NULL;
}

void *writer(void *arg) {
  pthread_rwlock_wrlock(&rwlock);
  data = 42;
  printf("Wrote: %d\n", data);
  pthread_rwlock_unlock(&rwlock);
  return NULL;
}

int main(void) {
  pthread_t r1, r2, w;
  pthread_create(&w, NULL, writer, NULL);
  pthread_create(&r1, NULL, reader, NULL);
  pthread_create(&r2, NULL, reader, NULL);
  pthread_join(w, NULL);
  pthread_join(r1, NULL);
  pthread_join(r2, NULL);
}
$ gcc -pthread -o rwlock main.c && ./rwlock
Wrote: 42
Read: 42
Read: 42

Answer section

Source and licence: C/C++ Interview Cheatsheet — Chang Ning Tsai · MIT

Related questions