Skip to content

pthread Condition Variable Internals

Overview

Condition variables allow threads to wait until a condition becomes true.

A condition variable does not store data.

It coordinates waiting.

Typical usage:

pthread_mutex_lock()

while (!condition)
    pthread_cond_wait()

consume()

pthread_mutex_unlock()

Motivation

Without condition variables:

lock

check

unlock

sleep

Another thread may update state during the gap.

Result:

notification lost

Condition variables solve this coordination problem.


Design Principle

Condition variables separate:

condition

and

notification

Condition:

data ready
queue not empty
buffer available

Notification:

wake event
wait queue
sequence

Condition stores truth.

Notification coordinates waiting.


Internal Structure

Conceptually:

pthread_cond

=

condition state
+
mutex
+
wait queue

Userspace implementation eventually reaches:

futex wait

futex wake

Wait Operation

Conceptually:

pthread_cond_wait()


save wait state


unlock mutex


sleep


wake


relock mutex

Important:

unlock

and

wait

must appear atomic.


Why While Loop Is Required

Correct:

while (!ready)
    pthread_cond_wait()

Avoid:

if (!ready)
    pthread_cond_wait()

Reasons:

  • spurious wakeup
  • multiple waiters
  • condition changed after wake

Producer Consumer Example

Consumer:

pthread_mutex_lock()

while (!ready)
    pthread_cond_wait()

consume()

pthread_mutex_unlock()

Producer:

pthread_mutex_lock()

ready = true

pthread_mutex_unlock()

pthread_cond_signal()

Minimal Condition Variable Model

Educational model:

ready
+
seq
+
mutex
+
futex

Roles:

Component Responsibility
ready condition
mutex protect shared state
seq notification generation
futex sleep and wake

Condition vs Notification

Example:

Consumer:

ready = false

seq = 10

Producer:

ready = true

seq = 11

wake

Consumer detects:

seq changed

and re-checks:

ready

This prevents missed notification.


Relationship with Futex

Conceptually:

pthread_cond_wait()


unlock


futex_wait()


lock

Signal:

sequence update


futex_wake()

Actual implementations may use:

requeue
multiple counters
generation tracking

Common Mistakes

Incorrect:

unlock

sleep

Correct:

unlock

wait

Incorrect:

if (!ready)

Correct:

while (!ready)

Incorrect:

store event in cond

Correct:

store state externally

Related Labs

  • Day61 futex wait semantics
  • Day61 mini condition variable

References

  • pthread_cond_wait()
  • pthread_cond_signal()
  • futex