Skip to content

Day59 Lab — pthread Condition Variable

Objective

Understand synchronization based on condition variables.


Architecture

Producer

Queue

Consumer

Synchronization:

  • mutex
  • not_empty
  • not_full

Experiment 1

Minimal wait/signal.

Verify:

  • cond_wait
  • predicate loop

Experiment 2

Spurious wakeup.

Send signal without changing predicate.

Observe:

worker wakeup

worker returns to wait


Experiment 3

Single item producer consumer.

Shared state:

bool has_item;
int item;

Experiment 4

Bounded queue.

Shared state:

count
head
tail

Conditions:

not_empty
not_full

Experiment 5

Timed wait.

Use:

pthread_cond_timedwait()

Observe:

timeout returns ETIMEDOUT.


Experiment 6

Multi consumer.

Compare:

signal
vs
broadcast

Observe:

broadcast wakes all waiters.

Only one may proceed.


Result

Condition variable is suitable for:

  • state machine
  • daemon
  • worker pool
  • event-driven systems