Skip to content

pthread_cond_wait()

Purpose

pthread_cond_wait() suspends the calling thread until a condition variable is signaled.

It is typically used together with a mutex to implement event-driven synchronization between threads.

The function atomically:

Unlock Mutex
Sleep
Wakeup
Re-lock Mutex

This atomic behavior prevents missed wakeup races.


#include <pthread.h>

Prototype

int pthread_cond_wait(pthread_cond_t *cond,
                      pthread_mutex_t *mutex);

Parameters

cond

Condition variable used for waiting.

Example:

pthread_cond_t cond;

mutex

Mutex protecting the shared condition.

Example:

pthread_mutex_t lock;

Return Value

Returns:

0

on success.

Otherwise returns a POSIX error code.


Typical Usage Pattern

pthread_mutex_lock(&lock);

while (!condition) {

    pthread_cond_wait(&cond,
                      &lock);
}

pthread_mutex_unlock(&lock);

Why Use a While Loop?

Incorrect:

if (!condition)
    pthread_cond_wait(&cond,
                      &lock);

Correct:

while (!condition)
    pthread_cond_wait(&cond,
                      &lock);

Reason

A waiting thread may wake up because of:

Condition satisfied

or:

Spurious wakeup

or:

Another thread consumed the condition first

Therefore the condition must always be rechecked.


Internal Behavior

Conceptually:

Thread A

mutex_lock()
condition == false
cond_wait()
unlock mutex
sleep

Another thread:

Thread B

mutex_lock()
update state
cond_signal()
mutex_unlock()

Waiting thread:

wake up
re-lock mutex
return

Producer-Consumer Example

Consumer:

pthread_mutex_lock(&lock);

while (queue_empty())
    pthread_cond_wait(&cond,
                      &lock);

item = queue_pop();

pthread_mutex_unlock(&lock);

Producer:

pthread_mutex_lock(&lock);

queue_push(item);

pthread_cond_signal(&cond);

pthread_mutex_unlock(&lock);

Why Mutex Is Required

The condition variable itself does not protect shared data.

Incorrect:

if (!condition)
    pthread_cond_wait(&cond,
                      NULL);

The condition must be protected by a mutex.

Correct:

pthread_mutex_lock(&lock);

while (!condition)
    pthread_cond_wait(&cond,
                      &lock);

pthread_mutex_unlock(&lock);

Common Mistake

Incorrect:

pthread_mutex_lock(&lock);

if (!condition)
    pthread_cond_wait(&cond,
                      &lock);

pthread_mutex_unlock(&lock);

Using:

if (...)

instead of:

while (...)

may lead to incorrect behavior.


Common Mistake

Incorrect:

condition = true;

pthread_cond_signal(&cond);

without holding the mutex.

This may introduce race conditions.


Advantages

Efficient Waiting

Threads sleep instead of busy-waiting.


Event Driven

Ideal for:

Producer-consumer
State transitions
Task coordination

Limitations

Requires Mutex

Condition variables must be used together with a mutex.


Predicate Required

A condition variable does not store state.

The program must maintain a shared predicate.

Example:

queue_not_empty
task_completed
data_ready