C
pthread_cond
Learn condition variables with pthread_cond.
pthread_cond
A condition variable lets one thread wake up another with a signal. It notifies when a shared condition changes.
First declare pthread_cond_t cond; and initialize with pthread_cond_init(&cond, NULL). The waiting side sleeps with pthread_cond_wait(&cond, &lock); it releases the lock while sleeping. The signaling side wakes it with pthread_cond_signal(&cond). The waiting side reacquires the lock when it wakes.
Producer-consumer
The classic example of condition variables is the producer-consumer pattern. The producer puts data and signals; the consumer takes data if available, otherwise waits.
The consumer waits in a loop with while (!ready) pthread_cond_wait(&cond, &lock);. Using while is important; cond_wait can return with spurious wakeup. The producer notifies with ready = 1; pthread_cond_signal(&cond);. The mutex protects the shared ready variable.
Exercise Producer-consumer
Declare int ready = 0;, pthread_mutex_t lock; and pthread_cond_t cond;. void *producer(void *arg): pthread_mutex_lock(&lock); ready = 1; pthread_cond_signal(&cond); pthread_mutex_unlock(&lock);. void *consumer(void *arg): pthread_mutex_lock(&lock); while (!ready) pthread_cond_wait(&cond, &lock); pthread_mutex_unlock(&lock);. Create both, join them and print printf("ready=%d\n", ready);.
Show example solution
#include <stdio.h>
#include <pthread.h>
int ready = 0;
pthread_mutex_t lock;
pthread_cond_t cond;
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);
}
pthread_mutex_unlock(&lock);
return NULL;
}
int main(void) {
pthread_mutex_init(&lock, NULL);
pthread_cond_init(&cond, NULL);
pthread_t tp, tc;
pthread_create(&tc, NULL, consumer, NULL);
pthread_create(&tp, NULL, producer, NULL);
pthread_join(tp, NULL);
pthread_join(tc, NULL);
printf("ready=%d\n", ready);
return 0;
}
Test yourself
-
What happens when pthread_cond_wait is called?
- It sends a signal
- It sleeps and releases the lock
- It acquires the lock
- The thread ends
Show answer
It sleeps and releases the lock — cond_wait sleeps and releases the lock while sleeping.
-
Match cond functions
- pthread_cond_wait
- Sleeps and waits
- pthread_cond_signal
- Wakes one
- pthread_cond_init
- Initializes cond
- spurious wakeup
- Spurious wake
-
cond_wait call
pthread_cond_____(&cond, &lock);
Show answer
pthread_cond_wait(&cond, &lock);
Next lesson: Thread safety