Lesson 14advancedThreads

Advanced Threads & Concurrency

Real-world concurrent programming. Features a CLI loading animation, dining philosophers, a thread-safe bank simulation, a shared canvas, spinner animations, and deep dives into condition variable pitfalls and broadcast vs signal semantics.

dining-philosophersproducer-consumermutexsemaphoreshared-memorycond_waitbroadcastfork
Prerequisites:13. Synchronization
1

CLI Loading Animation

A threaded loading spinner/progress bar for command-line interfaces.

01-cli.c
$ gcc -o cli_anim 01-cli.c -lpthread
$ ./cli_anim
Expected Outputclick Run to execute live
══════════════════════════════════════
  CLI loading animation with a spinner thread
══════════════════════════════════════


[Worker] Starting data fetch (simulating 5 seconds)...
Fetching data... |Fetching data... /Fetching data... -Fetching data... \Fetching data... |Fetching data... /Fetching data... -Fetching data... \Fetching data... |Fetching data... /Fetching data... -Fetching data... \Fetching data... |Fetching data... /Fetching data... -Fetching data... \Fetching data... |Fetching data... /Fetching data... -Fetching data... \Fetching data... |Fetching data... /Fetching data... -Fetching data... \Fetching data... |Fetching data... /Fetching data... -Fetching data... \Fetching data... |Fetching data... /Fetching data... -Fetching data... \Fetching data... |Fetching data... /Fetching data... -Fetching data... \Fetching data... |Fetching data... /Fetching data... -Fetching data... \Fetching data... |Fetching data... /Fetching data... -Fetching data... \Fetching data... |Fetching data... /Fetching data... -Fetching data... \Fetching data... |Fetching data... /[Worker] Data fetch completed!
Fetching data... Done!      
[Main] All tasks completed. The spinner ran while the worker fetched data.
2

Advanced CLI Simulator

A 285-line advanced terminal UI with progress bars, spinners, and status indicators — all thread-driven.

02-bit-more-cli/cli.c
$ gcc -o adv_cli 02-bit-more-cli/cli.c -lpthread
$ ./adv_cli
Expected Outputclick Run to execute live
══════════════════════════════════════
  Advanced CLI simulator with progress bars and spinners
══════════════════════════════════════


========== Multithreaded File Loader ==========
Commands:
1. load   - Simulate loading multiple files
2. status - Display loading progress
3. exit   - Exit the program
Enter command number: 1
2
3
Starting to load 5 files...
File_1.txt: [--------------------------------------------------] 0%
File_2.txt: [--------------------------------------------------] 0%
File_3.txt: [--------------------------------------------------] 0%
File_4.txt: [--------------------------------------------------] 0%
File_5.txt: [--------------------------------------------------] 0%

Press Ctrl+C to exit.
File_1.txt: [--------------------------------------------------] 0%
File_2.txt: [--------------------------------------------------] 0%
File_3.txt: [##------------------------------------------------] 5%
File_4.txt: [--------------------------------------------------] 0%
File_5.txt: [--------------------------------------------------] 0%

Press Ctrl+C to exit.
File_1.txt: [#-------------------------------------------------] 2%
File_2.txt: [###-----------------------------------------------] 6%
File_3.txt: [#######-------------------------------------------] 14%
File_4.txt: [#-------------------------------------------------] 2%
File_5.txt: [####----------------------------------------------] 9%

Press Ctrl+C to exit.
File_1.txt: [#######-------------------------------------------] 14%
File_2.txt: [########------------------------------------------] 16%
File_3.txt: [##########----------------------------------------] 21%
File_4.txt: [##########----------------------------------------] 20%
File_5.txt: [###########---------------------------------------] 23%

Press Ctrl+C to exit.
File_1.txt: [#########-----------------------------------------] 19%
File_2.txt: [############--------------------------------------] 25%
File_3.txt: [#################---------------------------------] 35%
File_4.txt: [######################----------------------------] 45%
File_5.txt: [#########################-------------------------] 50%

Press Ctrl+C to exit.
File_1.txt: [##########----------------------------------------] 21%
File_2.txt: [#############-------------------------------------] 26%
File_3.txt: [#################---------------------------------] 35%
File_4.txt: [######################----------------------------] 45%
File_5.txt: [#############################---------------------] 58%

Press Ctrl+C to exit.
File_1.txt: [###############-----------------------------------] 31%
File_2.txt: [####################------------------------------] 41%
File_3.txt: [#################################-----------------] 66%
File_4.txt: [#####################################-------------] 74%
File_5.txt: [######################################------------] 77%

Press Ctrl+C to exit.
File_1.txt: [#########################-------------------------] 50%
File_2.txt: [##########################------------------------] 53%
File_3.txt: [###########################################-------] 86%
File_4.txt: [#######################################-----------] 79%
File_5.txt: [######################################------------] 77%

Press Ctrl+C to exit.
File_1.txt: [###############################-------------------] 62%
File_2.txt: [#################################-----------------] 67%
File_3.txt: [#################################################-] 99%
File_4.txt: [#######################################-----------] 79%
File_5.txt: [###########################################-------] 86%

Press Ctrl+C to exit.
File_1.txt: [#################################-----------------] 67%
File_2.txt: [################################################--] 96%
File_3.txt: [##################################################] 100%
File_4.txt: [##################################################] 100%
File_5.txt: [############################################------] 89%

Press Ctrl+C to exit.
File_1.txt: [##################################----------------] 69%
File_2.txt: [##################################################] 100%
File_3.txt: [##################################################] 100%
File_4.txt: [##################################################] 100%
File_5.txt: [#############################################-----] 90%

Press Ctrl+C to exit.
File_1.txt: [############################################------] 88%
File_2.txt: [##################################################] 100%
File_3.txt: [##################################################] 100%
File_4.txt: [##################################################] 100%
File_5.txt: [###############################################---] 94%

Press Ctrl+C to exit.
File_1.txt: [#################################################-] 98%
File_2.txt: [##################################################] 100%
File_3.txt: [##################################################] 100%
File_4.txt: [##################################################] 100%
File_5.txt: [##################################################] 100%

Press Ctrl+C to exit.
File_1.txt: [##################################################] 100%
File_2.txt: [##################################################] 100%
File_3.txt: [##################################################] 100%
File_4.txt: [##################################################] 100%
File_5.txt: [##################################################] 100%

Press Ctrl+C to exit.

All files have been loaded successfully!

========== Multithreaded File Loader ==========
Commands:
1. load   - Simulate loading multiple files
2. status - Display loading progress
3. exit   - Exit the program
Enter command number: File_1.txt: [##################################################] 100%
File_2.txt: [##################################################] 100%
File_3.txt: [##################################################] 100%
File_4.txt: [##################################################] 100%
File_5.txt: [##################################################] 100%

Press Ctrl+C to exit.

========== Multithreaded File Loader ==========
Commands:
1. load   - Simulate loading multiple files
2. status - Display loading progress
3. exit   - Exit the program
Enter command number: Exiting program...
Program terminated gracefully.
Asks for input — sample input is one click away
3

Fork + Semaphore File Sync

Using named semaphores to synchronize file access between forked processes.

03-forks-mutex.c
$ gcc -o fork_sem 03-forks-mutex.c -lpthread
$ ./fork_sem
Expected Outputclick Run to execute live
══════════════════════════════════════
  Fork + Semaphore — File Sync
══════════════════════════════════════

[Parent] 5 child processes will write to 'shared_output.txt' protected by semaphore.

[Child 1, PID 2942] Acquired semaphore → wrote to file → releasing.
[Child 4, PID 2945] Acquired semaphore → wrote to file → releasing.
[Child 5, PID 2946] Acquired semaphore → wrote to file → releasing.
[Child 3, PID 2944] Acquired semaphore → wrote to file → releasing.
[Child 2, PID 2943] Acquired semaphore → wrote to file → releasing.

[Parent] All children finished. Check output: cat shared_output.txt
4

IPC Producer-Consumer

A 308-line producer-consumer using shared memory and semaphores across forked processes.

04-forks-mutex.c
$ gcc -o ipc_prodcons 04-forks-mutex.c -lpthread
$ ./ipc_prodcons
Expected Outputclick Run to execute live
══════════════════════════════════════
  IPC Producer-Consumer (Shared Memory)
══════════════════════════════════════

[Parent] 2 producers, 2 consumers, buffer size 5, 10 items each.
[Parent] Uses fork + shared memory + named semaphores.

[Producer 2] Produced item 200 → buffer[0]
[Consumer 1] Consumed item 200 ← buffer[0]
[Producer 1] Produced item 100 → buffer[1]
[Consumer 2] Consumed item 100 ← buffer[1]
[Producer 2] Produced item 201 → buffer[2]
[Producer 1] Produced item 101 → buffer[3]
[Consumer 1] Consumed item 201 ← buffer[2]
[Consumer 2] Consumed item 101 ← buffer[3]
[Producer 1] Produced item 102 → buffer[4]
[Producer 2] Produced item 202 → buffer[0]
[Consumer 1] Consumed item 102 ← buffer[4]
[Consumer 2] Consumed item 202 ← buffer[0]
[Producer 1] Produced item 103 → buffer[1]
[Producer 2] Produced item 203 → buffer[2]
[Producer 1] Produced item 104 → buffer[3]
[Producer 2] Produced item 204 → buffer[4]
[Consumer 1] Consumed item 103 ← buffer[1]
[Consumer 2] Consumed item 203 ← buffer[2]
[Producer 1] Produced item 105 → buffer[0]
[Producer 2] Produced item 205 → buffer[1]
[Consumer 1] Consumed item 104 ← buffer[3]
[Consumer 2] Consumed item 204 ← buffer[4]
[Producer 1] Produced item 106 → buffer[2]
[Producer 2] Produced item 206 → buffer[3]
[Producer 1] Produced item 107 → buffer[4]
[Consumer 1] Consumed item 105 ← buffer[0]
[Producer 2] Produced item 207 → buffer[0]
[Consumer 2] Consumed item 205 ← buffer[1]
[Producer 1] Produced item 108 → buffer[1]
[Consumer 1] Consumed item 106 ← buffer[2]
[Consumer 2] Consumed item 206 ← buffer[3]
[Producer 2] Produced item 208 → buffer[2]
[Producer 1] Produced item 109 → buffer[3]
[Producer 1] Finished — produced 10 items.
[Consumer 1] Consumed item 107 ← buffer[4]
[Consumer 2] Consumed item 207 ← buffer[0]
[Producer 2] Produced item 209 → buffer[4]
[Producer 2] Finished — produced 10 items.
[Consumer 1] Consumed item 108 ← buffer[1]
[Consumer 2] Consumed item 208 ← buffer[2]
[Consumer 1] Consumed item 109 ← buffer[3]
[Consumer 2] Consumed item 209 ← buffer[4]
[Consumer 1] Finished — consumed 10 items.
[Consumer 2] Finished — consumed 10 items.

[Parent] All producers and consumers finished. Shared memory released.
5

Dining Philosophers

The classic dining philosophers problem — five philosophers, five forks, mutex-based deadlock prevention.

05-forks-philosph.c
$ gcc -o philosophers 05-forks-philosph.c -lpthread
$ ./philosophers
Expected Outputclick Run to execute live
══════════════════════════════════════
  Dining Philosophers Problem
══════════════════════════════════════

[Main] Classic deadlock scenario solved with resource ordering.
[Main] Each philosopher picks up the lower-numbered fork first.

[Philosopher 1] 💭 Thinking... (round 1/3)
[Philosopher 0] 💭 Thinking... (round 1/3)
[Philosopher 3] 💭 Thinking... (round 1/3)
[Philosopher 4] 💭 Thinking... (round 1/3)
[Philosopher 2] 💭 Thinking... (round 1/3)
[Philosopher 1] Hungry! Reaching for fork 1 (lower-numbered first to prevent deadlock)
[Philosopher 1] ✓ Got fork 1. Now reaching for fork 2...
[Philosopher 1] ✓ Got fork 2. 🍝 EATING!
[Philosopher 0] Hungry! Reaching for fork 0 (lower-numbered first to prevent deadlock)
[Philosopher 3] Hungry! Reaching for fork 3 (lower-numbered first to prevent deadlock)
[Philosopher 3] ✓ Got fork 3. Now reaching for fork 4...
[Philosopher 3] ✓ Got fork 4. 🍝 EATING!
[Philosopher 0] ✓ Got fork 0. Now reaching for fork 1...
[Philosopher 2] Hungry! Reaching for fork 2 (lower-numbered first to prevent deadlock)
[Philosopher 4] Hungry! Reaching for fork 0 (lower-numbered first to prevent deadlock)
[Philosopher 3] Put down fork 4
[Philosopher 3] Put down fork 3 — done eating.
[Philosopher 3] 💭 Thinking... (round 2/3)
[Philosopher 1] Put down fork 2
[Philosopher 1] Put down fork 1 — done eating.
[Philosopher 1] 💭 Thinking... (round 2/3)
[Philosopher 0] ✓ Got fork 1. 🍝 EATING!
[Philosopher 2] ✓ Got fork 2. Now reaching for fork 3...
[Philosopher 2] ✓ Got fork 3. 🍝 EATING!
[Philosopher 0] Put down fork 1
[Philosopher 0] Put down fork 0 — done eating.
[Philosopher 0] 💭 Thinking... (round 2/3)
[Philosopher 4] ✓ Got fork 0. Now reaching for fork 4...
[Philosopher 4] ✓ Got fork 4. 🍝 EATING!
[Philosopher 2] Put down fork 3
[Philosopher 2] Put down fork 2 — done eating.
[Philosopher 2] 💭 Thinking... (round 2/3)
[Philosopher 3] Hungry! Reaching for fork 3 (lower-numbered first to prevent deadlock)
[Philosopher 3] ✓ Got fork 3. Now reaching for fork 4...
[Philosopher 1] Hungry! Reaching for fork 1 (lower-numbered first to prevent deadlock)
[Philosopher 1] ✓ Got fork 1. Now reaching for fork 2...
[Philosopher 1] ✓ Got fork 2. 🍝 EATING!
[Philosopher 4] Put down fork 4
[Philosopher 4] Put down fork 0 — done eating.
[Philosopher 4] 💭 Thinking... (round 2/3)
[Philosopher 3] ✓ Got fork 4. 🍝 EATING!
[Philosopher 1] Put down fork 2
[Philosopher 1] Put down fork 1 — done eating.
[Philosopher 1] 💭 Thinking... (round 3/3)
[Philosopher 2] Hungry! Reaching for fork 2 (lower-numbered first to prevent deadlock)
[Philosopher 2] ✓ Got fork 2. Now reaching for fork 3...
[Philosopher 0] Hungry! Reaching for fork 0 (lower-numbered first to prevent deadlock)
[Philosopher 0] ✓ Got fork 0. Now reaching for fork 1...
[Philosopher 0] ✓ Got fork 1. 🍝 EATING!
[Philosopher 3] Put down fork 4
[Philosopher 3] Put down fork 3 — done eating.
[Philosopher 3] 💭 Thinking... (round 3/3)
[Philosopher 2] ✓ Got fork 3. 🍝 EATING!
[Philosopher 0] Put down fork 1
[Philosopher 0] Put down fork 0 — done eating.
[Philosopher 0] 💭 Thinking... (round 3/3)
[Philosopher 4] Hungry! Reaching for fork 0 (lower-numbered first to prevent deadlock)
[Philosopher 4] ✓ Got fork 0. Now reaching for fork 4...
[Philosopher 4] ✓ Got fork 4. 🍝 EATING!
[Philosopher 1] Hungry! Reaching for fork 1 (lower-numbered first to prevent deadlock)
[Philosopher 1] ✓ Got fork 1. Now reaching for fork 2...
[Philosopher 2] Put down fork 3
[Philosopher 2] Put down fork 2 — done eating.
[Philosopher 2] 💭 Thinking... (round 3/3)
[Philosopher 1] ✓ Got fork 2. 🍝 EATING!
[Philosopher 3] Hungry! Reaching for fork 3 (lower-numbered first to prevent deadlock)
[Philosopher 3] ✓ Got fork 3. Now reaching for fork 4...
[Philosopher 4] Put down fork 4
[Philosopher 4] Put down fork 0 — done eating.
[Philosopher 3] ✓ Got fork 4. 🍝 EATING!
[Philosopher 4] 💭 Thinking... (round 3/3)
[Philosopher 0] Hungry! Reaching for fork 0 (lower-numbered first to prevent deadlock)
[Philosopher 0] ✓ Got fork 0. Now reaching for fork 1...
[Philosopher 1] Put down fork 2
[Philosopher 1] Put down fork 1 — done eating.
[Philosopher 0] ✓ Got fork 1. 🍝 EATING!
[Philosopher 1] Finished! Ate 3 times total.
[Philosopher 2] Hungry! Reaching for fork 2 (lower-numbered first to prevent deadlock)
[Philosopher 2] ✓ Got fork 2. Now reaching for fork 3...
[Philosopher 3] Put down fork 4
[Philosopher 3] Put down fork 3 — done eating.
[Philosopher 2] ✓ Got fork 3. 🍝 EATING!
[Philosopher 3] Finished! Ate 3 times total.
[Philosopher 4] Hungry! Reaching for fork 0 (lower-numbered first to prevent deadlock)
[Philosopher 0] Put down fork 1
[Philosopher 0] Put down fork 0 — done eating.
[Philosopher 0] Finished! Ate 3 times total.
[Philosopher 4] ✓ Got fork 0. Now reaching for fork 4...
[Philosopher 4] ✓ Got fork 4. 🍝 EATING!
[Philosopher 2] Put down fork 3
[Philosopher 2] Put down fork 2 — done eating.
[Philosopher 2] Finished! Ate 3 times total.
[Philosopher 4] Put down fork 4
[Philosopher 4] Put down fork 0 — done eating.
[Philosopher 4] Finished! Ate 3 times total.

--- Dining Status (from shared memory) ---
  Philosopher 0: ate 3 times
  Philosopher 1: ate 3 times
  Philosopher 2: ate 3 times
  Philosopher 3: ate 3 times
  Philosopher 4: ate 3 times

--- Dining Philosophers simulation completed (no deadlocks!) ---
6

Thread-Safe Counter

A mutex-protected counter incremented by multiple threads — the canonical thread safety example.

06-pthreads.c
/*
 * 06-pthreads.c — Thread-safe counter with mutex
 *
 * Key concepts: pthread_mutex_lock/unlock, shared counter, thread safety
 * Compile: gcc -o counter 06-pthreads.c -lpthread
 * Run:     ./prog
 */
// File: thread_safe_counter.c
// Compile with: gcc -Wall -pthread -o thread_safe_counter thread_safe_counter.c

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

#define NUM_THREADS 5
#define INCREMENTS_PER_THREAD 1000000

// Shared counter
long long counter = 0;

// Mutex to protect the counter
pthread_mutex_t counter_mutex;

void* increment_counter(void* arg) {
    for (int i = 0; i < INCREMENTS_PER_THREAD; i++) {
        // Lock the mutex before modifying the counter
        pthread_mutex_lock(&counter_mutex);
        
        // Critical section
        counter++;
        
        // Unlock the mutex after modification
        pthread_mutex_unlock(&counter_mutex);
    }
    pthread_exit(NULL);
}

int main() {
    printf("\n");
    pthread_t threads[NUM_THREADS];
    int rc;

    // Initialize the mutex
    if (pthread_mutex_init(&counter_mutex, NULL) != 0) {
        perror("Mutex initialization failed");
        exit(EXIT_FAILURE);
    }

    printf("[Main] %d threads, each incrementing %d times = %d total.\n", NUM_THREADS, INCREMENTS_PER_THREAD, NUM_THREADS * INCREMENTS_PER_THREAD);
    printf("[Main] Using mutex for every increment (safe but slow).\n\n");

    for (long t = 0; t < NUM_THREADS; t++) {
        rc = pthread_create(&threads[t], NULL, increment_counter, NULL);
        if (rc) {
            fprintf(stderr, "[Main] ERROR: pthread_create failed (thread %ld, rc=%d)\n", t, rc);
            exit(EXIT_FAILURE);
        }
        printf("[Main] Thread %ld created\n", t);
    }

    printf("[Main] Waiting for all threads...\n");
    for (int t = 0; t < NUM_THREADS; t++) {
        pthread_join(threads[t], NULL);
    }

    pthread_mutex_destroy(&counter_mutex);

    long long expected = (long long)NUM_THREADS * INCREMENTS_PER_THREAD;
    printf("\n══════════════════════════════════════\n");
    printf("  Expected: %lld\n", expected);
    printf("  Actual:   %lld %s\n", counter, counter == expected ? "✓ correct!" : "← BUG!");
    printf("══════════════════════════════════════\n");
    return 0;
}
$ gcc -o safe_counter 06-pthreads.c -lpthread
$ ./safe_counter
Expected Outputclick Run to execute live
[Main] 5 threads, each incrementing 1000000 times = 5000000 total.
[Main] Using mutex for every increment (safe but slow).

[Main] Thread 0 created
[Main] Thread 1 created
[Main] Thread 2 created
[Main] Thread 3 created
[Main] Thread 4 created
[Main] Waiting for all threads...

══════════════════════════════════════
  Expected: 5000000
  Actual:   5000000 ✓ correct!
══════════════════════════════════════
7

Thread Logging

Multiple threads writing to a shared log with mutex-protected access.

07-pthreads-2.c
$ gcc -o thread_log 07-pthreads-2.c -lpthread
$ ./thread_log
Expected Outputclick Run to execute live
══════════════════════════════════════
  Thread-Safe File Logging
══════════════════════════════════════

[Main] 5 threads each write 1000 log entries to thread_log.txt.
[Main] Mutex ensures log lines don't get interleaved.

[Main] All threads finished. 5000 log entries written to thread_log.txt.
[Main] Check with: wc -l thread_log.txt (should be 5000)
8

Bank Simulation

A multi-threaded bank simulation — concurrent deposits and withdrawals with mutex-protected account balances.

08-cool-bank.c
$ gcc -o bank 08-cool-bank.c -lpthread
$ ./bank
Expected Outputclick Run to execute live
══════════════════════════════════════
  Bank Simulation — Concurrent Transfers
══════════════════════════════════════

[Main] 6 threads: 3 deposit, 3 withdraw. Each does 1000 operations ($1 each).
[Main] With mutex: balance should end at $0 (deposits == withdrawals).

[Deposit Thread] Finished — deposited $1000 total
[Withdraw Thread] Finished — withdrew $1000 total
[Withdraw Thread] Finished — withdrew $1000 total
[Deposit Thread] Finished — deposited $1000 total
[Withdraw Thread] Finished — withdrew $1000 total
[Deposit Thread] Finished — deposited $1000 total

══════════════════════════════════════
  Final balance: $0 (expected: $0) ✓
══════════════════════════════════════
9

Shared Canvas

Multiple threads drawing on a shared 2D canvas, with mutex protection to prevent visual corruption.

09-cool-canvas.c
$ gcc -o canvas 09-cool-canvas.c -lpthread
$ ./canvas
Expected Outputclick Run to execute live
══════════════════════════════════════
  Shared Canvas — Concurrent Drawing
══════════════════════════════════════

. . . . . . . . . . . . . . . . . . . . 
. . . . . . . . . . . . . . . . . . . . 
. . . . . . . . . . . . . . . . . . . . 
. . . . . . . . . . . . . . . . . . . . 
. . . . . . . . . . . . . . . . . . . . 
. . . . . . . . . . . . . . . . . . . . 
. . . . . . . . . . . . . . . . . . . . 
. . . . . . . . . . . . . . . . . . . . 
. . . . . . . . . . . . . . . . . . . . 
. . . . . . . . . . . . . . . . . . . . 
. . . . . . . . . . . . . . . . . . . . 
. . . . . . . . . . . . . . . . . . . . 
. . D D . . . . . . . . . . . . . . . . 
. . D D . . . . . . . . . . . . . . . . 
. . D D . . . . . A A . E E . . . . . . 
. . . . . . . . . A A . E E . . . . . . 
B B . . . . . . . . . . E E . . . . . . 
B B . . . . . . . . C C . . . . . . . . 
. . . . . . . . . . C C . . . . . . . . 
. . . . . . . . . . . . . . . . . . . . 
. . . . . . . . . . . . . . . . . . . . 
. . . . . . . . . . . . . . . . . . . . 
. . D D . . . . B B D D . . . . . . . . 
. . D D . . . . B B D D . . . . . . . . 
. . D C C C E E B B D D E E . . . . . . 
. . . C C C E E B B D D E E . . . . . . 
B B . C C C . . . . . . E E . . . . . . 
B B . . . . . . . . C C . . . . . . . . 
. . . . . . . . . . C C . . . . . . . . 
. . . . . . . . . . . . . . . . . . . . 
. . . . . . . . . . . . A A A . . . . . 
. . . . . . . . . . . . A A A . . . . . 
. . D D . . . . B B D D A A A . . . . . 
. . D D . . . . B B D D A A A . . . . . 
. . D C C C E E B B D D E E . . . . . . 
. . . C C C E E B B D D E E . . . . . . 
B B . C C C . . . . . . E E . . . . . . 
B B . . . . . . . . C C . . . . . . . . 
. . . . . . . . . . C C . . . . . . . . 
. . . . . . . . . . . . . . . . . . . . 
. . . . . . . . . . . . A A A . . . . . 
. . . . . . . . . . . . A A A . . . . . 
. . D D . . . . B B D D A A A . . . . . 
. . D D . . . . B B D D A A A . . . . . 
. B B B C C E E B B D D E E . . . . . . 
. B B B C C E E B B C C C E E E E . . . 
B B B B C D D D D . C C C E E E E . . . 
B B . . . D D D D . C C C . . . . . . . 
. . . . . D D D D . C C . . . . . . . . 
. . . . . . . . . . . . . . . . . . . . 
. . . . . . . . . . . . A A A A A A . . 
. . . . . . . . . . . . A A A A A A . . 
. . D D . . . . B B D D A A A A A A . . 
. . D D . . . . B B D D A A A . . . . . 
. B B B C C E E B B D D E E . . . . . . 
. B B B C C E E B B C C C E E E E . . . 
B B B B C D D D D . C C C E E E E . . . 
B B . . . D D D D . C C C . . . . . . . 
. . . . . D D D D . C C . . . . . . . . 
. . . . . . . . . . . . . . . . . . . . 
. . . . B B . . . . . . A A A A A A . . 
. . . . B B . . . . . . A A A A A A . . 
. . D D . . . . B B D D A A A A A A . . 
. . D D . . . . B B D D A A A . D D D D 
. B B B C C E C C B D D E E . . D D D D 
. B B B C C E E E E C C C E E E E . . . 
B B B B C D E E E E C C C E E E E . . . 
B B . . . D E E E E C C C . . . . . . . 
. . . . . D D D D . C C . . . . . . . . 
. . . . . . . . . . . . . . . . . . . . 
. . . . B B . . . . . . A A A A A A . . 
. . . . B B . . . . . . A A A A A A . . 
. . D D . . . . B B D D A A A A A A . . 
. . D D . . . . B B D D A A A . D D D D 
. B B B C C E C C B D D E E . . D D D D 
. B B B C C E E E E C C C E E E A A . . 
B B B B C D E E E E C C C E E E A A . . 
B B . . . D E E E E C C C . . . . . . . 
. . . . . D D D D . C C . . . . . . . . 
. . . . . . . . . . . . . . . . . . . . 
. . . . B B . . . . . . A A A A A A . . 
. . . . B B C C . . . A A A A A A A . . 
. . D D . . C C B B D A A A A A A A . . 
. . D D . . . . B B D A A A A . E E E D 
. B B B C C E C C B B A A A A . E E E D 
. B B B C C E E E E B B B E E E A A . . 
B B B B C D E E E E B B B E E E A A . . 
D D D D . D E E E E B B B . . . . . . . 
D D D D . D D D D . C C . . . . . . . . 
D D D D . . . . . . . . . . . . . . . . 
. . . . B B . . . . . . A A A A A A . . 
. . . . B B C C . . . A A A A A A A . . 
. . D D . . C C B B D A A A A A A A . . 
. . D D . . . . B B D A A A A . E E E D 
. B B B C C E C C B B A A A A . E E E D 
. B B B C C E E E E B B B E E E A A . . 
B B B B C D E E E E B B B E E E A A . . 
D D D D . D E E E E B B B . . . . . . . 
D D D D . D D D D . C C . . . . . . . . 
D D D D . . . . . . . . . . . . . . . . 
. D D . B B . . . . . A A A A A A A . . 
. D D . B B C C . . . A A A A A A A . . 
. E E D . . C C B B D A A A A A A A . . 
. E E D . . . . B B D A A A A . E E E D 
. E E B C C E C C B B A A A A . E E E D 
. B B B C B B E C C C C B E E E A A . . 
B B B B C B B E C C C C B E E E A A . . 
D D D D . B B E C C C C B . . . . . . . 
D D D D . B B D D . C C . . . . . . . . 
D D D D . . . . . . . . . . . . . . . . 
. D D . B B . . . . . A A A A A A A . . 
. D D . B B C C . . . A A A A A A A . . 
. E E D . . C C B B D A A A A A A A . . 
. E E D . . . . B B D A A A A . E E E D 
. E E B C C E C C B B A A A A . E E E D 
. B B B C B B E C C C C B E E E A A . . 
B B B B C B B E C C C C B E E E A A . . 
D D D D . B B E C C C C B . . . . . . . 
D D D D . B B D D . C C . . . . . . . . 
D D D D . . . . . . . . . . . . . . . . 
. D D . C C C . . . . A A A A A A A . . 
. D D . C C C C . . . A A A A A A A . . 
. E E D C C C C B E E E A A A D D A . . 
A A E D C C C . B E E E A A A D D E E D 
A A E B C C E C C B B A A A A D D E E D 
A A B B C B B E C C C C B E E E A A . . 
A A B B B B B E C C C C B E E E A A . . 
D B B B B B B E C C C C B . . . . . . . 
D B B B B B B D D . C C . . . . . . . . 
D D D D . . . . . . . . . . . . . . . . 
. D D . C C C . . . . A A A A A A A . . 
. D D . C C C C . . . A A A A A A A . . 
. E E D C C C C B E E E A A A D D A . . 
A A E D C C C . B E E E A A A D D E E D 
A A E B C C E C C B B A A A A D D E E D 
A A B B C B B E C C C C B E E E A A . . 
A A B B B B B E C C C C B E E E A A . . 
D B B B B B B E C C C C B . . . . . . . 
D B B B B B B D D . C C . . . . . . . . 
D D D D . . . . . . . . . . . . . . . . 
. D D . C C C . . . . A A A A A A A . . 
. D D . C C C C . . . A A A A A A A . . 
. E E D C C C C B E E E A A A D D A . . 
A A E D C C C . B E E E A A A D D E E D 
D D B B B C C C C B B A A A A D D E E D 
D D B B B B B E C C C C B E E E A A . . 
D D B B B B B E C C C C B E E E E E . . 
D D B A A A B E C C C C B . . . E E . . 
D B B A A A B D D . C C . . . . E E . . 
D D D A A A . . . . . . . . . . E E . . 
. D D . C C C . . . . A A A A A A A . . 
. D D . C C C C . . . A A A A A A A . . 
. E E D C C C C B E E E A A A D D A . . 
A A E D C C C . B E E E A A A D D E E D 
D D B B B C C C C B B A A A A D D E E D 
D D B B B B B E C C C C B E E E A A . . 
D D B B B B B E C C C C B E E E E E . . 
D D B A A A B E C C C C B . . . E E . . 
D B B A A A B D D . C C . . . . E E . . 
D D D A A A . . . . . . . . . . E E . . 
. D D . C C C . . . . A A A A A A A . . 
. D D . C C C C . . . A A A A A A A D D 
. E E D C C E E B B E E A A A A A A A D 
A A E D C C E E B B E E A A C C C A A D 
D D B B B C E E E E B A A A C C C A A D 
D D B B B B B E C C C C B E C C C A . . 
D D B B B B B E C C C C B E C C C E . . 
D D B A A A B E C C C C B . . . E E . . 
D B B A A A B D D . C C . . . . E E . . 
D D D A A A . . . . . . . . . . E E . . 
. D D . C C C . . . . A A A A A A A . . 
. D D . C C C C . . . A A A A A A A D D 
. E E D C C E E B B E E A A A A A A A D 
A A E D C C E E B B E E A A C C C A A D 
D D B B B C E E E E B A A A C C C A A D 
D D B B B B B E C C C C B E C C C A . . 
D D B B B B B E C C C C B E C C C E . . 
D D B A A A B E C C C C B . . . E E . . 
D B B A A A B D D . C C . . . . E E . . 
D D D A A A . . . . . . . . . . E E . . 
^C

[runs until stopped — the site stops it after 8s]
Runs until stopped — stops automatically after 8s
10

Spinner Animations

Multiple concurrent terminal spinner animations — each thread runs its own spinner pattern.

10-spinners.c
$ gcc -o spinners 10-spinners.c -lpthread
$ ./spinners
Expected Outputclick Run to execute live
══════════════════════════════════════
  Concurrent Spinner Animations
══════════════════════════════════════

Spinner 1: |Spinner 1: /Spinner 1: -Spinner 1: \Spinner 1: |Spinner 1: /Spinner 1: -Spinner 1: \Spinner 1: |Spinner 1: /Spinner 2: |Spinner 1: -Spinner 2: /Spinner 1: \Spinner 2: -Spinner 1: |Spinner 2: \Spinner 1: /Spinner 2: |Spinner 1: -Spinner 2: /Spinner 1: \Spinner 2: -Spinner 1: |Spinner 2: \Spinner 1: /Spinner 2: |Spinner 1: -Spinner 2: /Spinner 1: \Spinner 3: |Spinner 2: -Spinner 1: |Spinner 3: /Spinner 2: \Spinner 1: /Spinner 3: -Spinner 2: |Spinner 1: -Spinner 3: \Spinner 2: /Spinner 1: \Spinner 2: -Spinner 3: |Spinner 1: |Spinner 3: /Spinner 2: \Spinner 1: /Spinner 3: -Spinner 2: |Spinner 1: -Spinner 3: \Spinner 2: /Spinner 1: \Spinner 3: |Spinner 2: -Spinner 1: |Spinner 3: /Spinner 2: \Spinner 1: /Spinner 4: |Spinner 2: |Spinner 3: -Spinner 1: -Spinner 4: /Spinner 2: /Spinner 3: \Spinner 1: \Spinner 4: -Spinner 2: -Spinner 3: |Spinner 1: |Spinner 4: \Spinner 2: \Spinner 3: /Spinner 1: /Spinner 4: |Spinner 2: |Spinner 3: -Spinner 1: -Spinner 4: /Spinner 2: /Spinner 3: \Spinner 1: \Spinner 4: -Spinner 2: -Spinner 3: |Spinner 1: |Spinner 4: \Spinner 2: \Spinner 3: /Spinner 1: /Spinner 4: |Spinner 2: |Spinner 3: -Spinner 1: -Spinner 4: /Spinner 2: /Spinner 3: \Spinner 1: \Spinner 5: |Spinner 4: -Spinner 2: -Spinner 3: |Spinner 1: |Spinner 5: /Spinner 4: \Spinner 2: \Spinner 3: /Spinner 1: /Spinner 5: -Spinner 4: |Spinner 2: |Spinner 3: -Spinner 1: -Spinner 5: \Spinner 4: /Spinner 2: /Spinner 3: \Spinner 1: \Spinner 5: |Spinner 4: -Spinner 2: -Spinner 3: |Spinner 1: |Spinner 5: /Spinner 4: \Spinner 2: \Spinner 3: /Spinner 1: /Spinner 5: -Spinner 4: |Spinner 2: |Spinner 3: -Spinner 1: -Spinner 5: \Spinner 4: /Spinner 3: \Spinner 2: /Spinner 1: \Spinner 5: |Spinner 4: -Spinner 3: |Spinner 2: -Spinner 1: |Spinner 5: /Spinner 4: \Spinner 2: \Spinner 1: /Spinner 3: /Spinner 6: |Spinner 5: -Spinner 4: |Spinner 1: -Spinner 3: -Spinner 2: |Spinner 5: \Spinner 6: /Spinner 4: /Spinner 3: \Spinner 1: \Spinner 2: /Spinner 5: |Spinner 6: -Spinner 4: -Spinner 3: |Spinner 1: |Spinner 2: -Spinner 5: /Spinner 4: \Spinner 6: \Spinner 3: /Spinner 1: /Spinner 2: \Spinner 5: -Spinner 4: |Spinner 6: |Spinner 1: -Spinner 2: |Spinner 3: -Spinner 5: \Spinner 4: /Spinner 6: /Spinner 2: /Spinner 3: \Spinner 1: \Spinner 5: |Spinner 4: -Spinner 6: -Spinner 2: -Spinner 1: |Spinner 3: |Spinner 5: /Spinner 4: \Spinner 6: \Spinner 2: \Spinner 1: /Spinner 3: /Spinner 5: -Spinner 4: |Spinner 6: |Spinner 2: |Spinner 1: -Spinner 3: -Spinner 5: \Spinner 4: /Spinner 6: /Spinner 1: \Spinner 2: /Spinner 3: \Spinner 7: |Spinner 5: |Spinner 4: -Spinner 1: |Spinner 6: -Spinner 3: |Spinner 2: -Spinner 7: /Spinner 5: /Spinner 4: \Spinner 1: /Spinner 6: \Spinner 3: /Spinner 2: \Spinner 7: -Spinner 5: -Spinner 4: |Spinner 1: -Spinner 6: |Spinner 2: |Spinner 3: -Spinner 7: \Spinner 5: \Spinner 4: /Spinner 6: /Spinner 1: \Spinner 3: \Spinner 2: /Spinner 7: |Spinner 5: |Spinner 4: -Spinner 6: -Spinner 1: |Spinner 3: |Spinner 2: -Spinner 7: /Spinner 5: /Spinner 4: \Spinner 6: \Spinner 1: /Spinner 3: /Spinner 2: \Spinner 7: -Spinner 5: -Spinner 4: |Spinner 6: |Spinner 1: -Spinner 3: -Spinner 2: |Spinner 7: \Spinner 5: \Spinner 4: /Spinner 6: /Spinner 1: \Spinner 2: /Spinner 3: \Spinner 7: |Spinner 5: |Spinner 4: -Spinner 6: -Spinner 1: |Spinner 2: -Spinner 3: |Spinner 7: /Spinner 5: /Spinner 4: \Spinner 6: \Spinner 1: /Spinner 2: \Spinner 3: /Spinner 8: |Spinner 7: -Spinner 5: -Spinner 4: |Spinner 6: |Spinner 1: -Spinner 2: |Spinner 3: -Spinner 8: /Spinner 7: \Spinner 5: \Spinner 4: /Spinner 6: /Spinner 1: \Spinner 2: /Spinner 3: \Spinner 8: -Spinner 7: |Spinner 5: |Spinner 4: -Spinner 6: -Spinner 1: |Spinner 2: -Spinner 3: |Spinner 8: \Spinner 7: /Spinner 5: /Spinner 4: \Spinner 6: \Spinner 1: /Spinner 2: \Spinner 3: /Spinner 8: |Spinner 7: -Spinner 5: -Spinner 4: |Spinner 6: |Spinner 1: -Spinner 2: |Spinner 3: -Spinner 8: /Spinner 7: \Spinner 5: \Spinner 4: /Spinner 6: /Spinner 1: \Spinner 2: /Spinner 3: \Spinner 8: -Spinner 7: |Spinner 5: |Spinner 4: -Spinner 6: -Spinner 1: |Spinner 2: -Spinner 3: |Spinner 8: \Spinner 7: /Spinner 5: /Spinner 4: \Spinner 6: \Spinner 1: /Spinner 2: \Spinner 3: /Spinner 8: |Spinner 7: -Spinner 5: -Spinner 4: |Spinner 6: |Spinner 1: -Spinner 2: |Spinner 3: -Spinner 8: /Spinner 7: \Spinner 5: \Spinner 4: /Spinner 1: \Spinner 6: /Spinner 2: /Spinner 3: \Spinner 9: |Spinner 8: -Spinner 7: |Spinner 5: |Spinner 4: -Spinner 1: |Spinner 6: -Spinner 2: -Spinner 3: |Spinner 9: /Spinner 8: \Spinner 7: /Spinner 5: /Spinner 4: \Spinner 6: \Spinner 1: /Spinner 2: \Spinner 3: /Spinner 9: -Spinner 8: |Spinner 7: -Spinner 5: -Spinner 4: |Spinner 6: |Spinner 1: -Spinner 2: |Spinner 3: -Spinner 8: /Spinner 9: \Spinner 7: \Spinner 5: \Spinner 4: /Spinner 1: \Spinner 6: /Spinner 2: /Spinner 3: \Spinner 8: -Spinner 9: |Spinner 7: |Spinner 5: |Spinner 4: -Spinner 6: -Spinner 1: |Spinner 3: |Spinner 2: -^C

[runs until stopped — the site stops it after 8s]
Runs until stopped — stops automatically after 8s
11

Condition Variable Pitfalls

What goes wrong when you use condition variables incorrectly — missed signals and spurious wakeups.

11-5-cond-waiting-bad.c
/*
 * 11-5-cond-waiting-bad.c — Condition variable pitfalls — what can go wrong
 *
 * Key concepts: Missed signals, spurious wakeups, why while-loop is needed
 * Compile: gcc -o cond_bad 11-5-cond-waiting-bad.c -lpthread
 * Run:     ./cond_bad
 */
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>

#define NUM_THREADS 2

pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
int condition_met = 0;

void* thread_func(void* arg) {
    long id = (long)arg;
    printf("[Thread %ld] Starting — will wait for condition...\n", id);
    pthread_mutex_lock(&mutex);
    while (!condition_met) {
        printf("[Thread %ld] Calling cond_wait (blocking)...\n", id);
        pthread_cond_wait(&cond, &mutex);
        printf("[Thread %ld] Woke up! Checking condition...\n", id);
    }
    pthread_mutex_unlock(&mutex);

    printf("[Thread %ld] Condition met — proceeding.\n", id);
    return NULL;
}

int main() {
    printf("\n");
    printf("══════════════════════════════════════\n");
    printf("  Condition Variable Pitfalls\n");
    printf("══════════════════════════════════════\n\n");
    printf("[Main] BUG DEMO: signals sent BEFORE threads are created!\n");
    printf("[Main] The signals are lost — threads will block forever.\n\n");

    pthread_t threads[NUM_THREADS];

    // BUG: Sending signals before any thread is waiting
    printf("[Main] Sending cond_signal #1... (nobody is listening!)\n");
    pthread_cond_signal(&cond);
    printf("[Main] Sending cond_signal #2... (still nobody listening!)\n");
    pthread_cond_signal(&cond);
    printf("[Main] Both signals are LOST — they don't queue up.\n\n");

    // Create threads after signals — they'll never wake up
    for (long i = 0; i < NUM_THREADS; i++) {
        pthread_create(&threads[i], NULL, thread_func, (void*)i);
    }

    printf("[Main] Threads created. They're waiting for signals that already fired.\n");
    printf("[Main] This program will hang forever! (Ctrl+C to exit)\n");
    printf("[Main] Fix: set condition_met=1 before signaling, or signal after threads start.\n");

    for (int i = 0; i < NUM_THREADS; i++) {
        pthread_join(threads[i], NULL);
    }

    pthread_mutex_destroy(&mutex);
    pthread_cond_destroy(&cond);

    return 0;
}
$ gcc -o cond_bad 11-5-cond-waiting-bad.c -lpthread
$ ./cond_bad
Expected Outputclick Run to execute live
══════════════════════════════════════
  Condition Variable Pitfalls
══════════════════════════════════════

[Main] BUG DEMO: signals sent BEFORE threads are created!
[Main] The signals are lost — threads will block forever.

[Main] Sending cond_signal #1... (nobody is listening!)
[Main] Sending cond_signal #2... (still nobody listening!)
[Main] Both signals are LOST — they don't queue up.

[Main] Threads created. They're waiting for signals that already fired.
[Main] This program will hang forever! (Ctrl+C to exit)
[Main] Fix: set condition_met=1 before signaling, or signal after threads start.
[Thread 1] Starting — will wait for condition...
[Thread 1] Calling cond_wait (blocking)...
[Thread 0] Starting — will wait for condition...
[Thread 0] Calling cond_wait (blocking)...
^C

[runs until stopped — the site stops it after 6s]
Runs until stopped — stops automatically after 6sHangs forever on purpose: the signal is sent before anyone waits (a lost wakeup)
12

Simple Condition Variable

The correct way to use pthread_cond_wait with a predicate in a while loop.

12-cond-simple.c
/*
 * 12-cond-simple.c — Simple correct condition variable usage
 *
 * Key concepts: pthread_cond_wait in while loop, predicate check pattern
 * Compile: gcc -o cond_ok 12-cond-simple.c -lpthread
 * Run:     ./cond_ok
 */
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>

// Spurious wakeups: https://en.wikipedia.org/wiki/Spurious_wakeup
// This is why we use while() not if() around cond_wait!

#define NUM_THREADS 20

pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
int condition_met = 0;

void* thread_func(void* arg) {
    long id = (long)arg;

    pthread_mutex_lock(&mutex);
    while (!condition_met) {
        // while-loop protects against spurious wakeups:
        // if a thread wakes without condition_met, it goes back to sleep
        pthread_cond_wait(&cond, &mutex);
    }
    pthread_mutex_unlock(&mutex);

    printf("[Thread %2ld] Condition met — proceeding!\n", id);
    return NULL;
}

int main() {
    printf("\n");
    printf("══════════════════════════════════════\n");
    printf("  Correct Condition Variable Usage\n");
    printf("══════════════════════════════════════\n\n");
    printf("[Main] Creating %d threads. All will wait on cond_wait.\n", NUM_THREADS);
    printf("[Main] After 2 seconds, main sets condition=1 and signals each one.\n\n");

    pthread_t threads[NUM_THREADS];

    for (long i = 0; i < NUM_THREADS; i++) {
        pthread_create(&threads[i], NULL, thread_func, (void*)i);
    }
    printf("[Main] All %d threads created and waiting.\n", NUM_THREADS);

    sleep(2);

    printf("\n[Main] Setting condition_met = 1\n");
    pthread_mutex_lock(&mutex);
    condition_met = 1;
    pthread_mutex_unlock(&mutex);

    printf("[Main] Sending cond_signal to each thread (one at a time)...\n\n");
    for (int i = 0; i < NUM_THREADS; i++) {
        pthread_cond_signal(&cond);
        usleep(100000); // Small delay to observe sequential waking
    }

    for (int i = 0; i < NUM_THREADS; i++) {
        pthread_join(threads[i], NULL);
    }

    pthread_mutex_destroy(&mutex);
    pthread_cond_destroy(&cond);

    printf("\n[Main] All %d threads finished. Compare with 11-5 (the broken version).\n", NUM_THREADS);
    return 0;
}
$ gcc -o cond_simple 12-cond-simple.c -lpthread
$ ./cond_simple
Expected Outputclick Run to execute live
══════════════════════════════════════
  Correct Condition Variable Usage
══════════════════════════════════════

[Main] Creating 20 threads. All will wait on cond_wait.
[Main] After 2 seconds, main sets condition=1 and signals each one.

[Main] All 20 threads created and waiting.

[Main] Setting condition_met = 1
[Main] Sending cond_signal to each thread (one at a time)...

[Thread  1] Condition met — proceeding!
[Thread  0] Condition met — proceeding!
[Thread  2] Condition met — proceeding!
[Thread  8] Condition met — proceeding!
[Thread 10] Condition met — proceeding!
[Thread 12] Condition met — proceeding!
[Thread 14] Condition met — proceeding!
[Thread 15] Condition met — proceeding!
[Thread 17] Condition met — proceeding!
[Thread 19] Condition met — proceeding!
[Thread  5] Condition met — proceeding!
[Thread 11] Condition met — proceeding!
[Thread 16] Condition met — proceeding!
[Thread 18] Condition met — proceeding!
[Thread 13] Condition met — proceeding!
[Thread  7] Condition met — proceeding!
[Thread  6] Condition met — proceeding!
[Thread  3] Condition met — proceeding!
[Thread  4] Condition met — proceeding!
[Thread  9] Condition met — proceeding!

[Main] All 20 threads finished. Compare with 11-5 (the broken version).
13

Broadcast vs Signal

Comparing pthread_cond_signal (wake one) and pthread_cond_broadcast (wake all) — when to use each.

13-broadcast.c
/*
 * 13-broadcast.c — Broadcast vs Signal — pthread_cond_broadcast
 *
 * Key concepts: pthread_cond_signal (wake one) vs pthread_cond_broadcast (wake all)
 * Compile: gcc -o broadcast 13-broadcast.c -lpthread
 * Run:     ./broadcast
 */
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>

#define NUM_THREADS 20

pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
int condition_met = 0;

void* thread_func(void* arg) {
    long id = (long)arg;

    pthread_mutex_lock(&mutex);
    while (!condition_met) {
        pthread_cond_wait(&cond, &mutex);
        // When broadcast fires, ALL threads wake up simultaneously.
        // But only one can hold the mutex at a time — they take turns.
        printf("[Thread %2ld] Woke up! Re-checking condition (mutex acquired)...\n", id);
    }
    pthread_mutex_unlock(&mutex);

    printf("[Thread %2ld] Proceeding — condition is true.\n", id);
    return NULL;
}

int main() {
    printf("\n");
    printf("══════════════════════════════════════\n");
    printf("  Broadcast vs Signal\n");
    printf("══════════════════════════════════════\n\n");
    printf("[Main] cond_signal:    wakes ONE waiting thread\n");
    printf("[Main] cond_broadcast: wakes ALL waiting threads\n\n");
    printf("[Main] Creating %d threads, all will call cond_wait...\n", NUM_THREADS);

    pthread_t threads[NUM_THREADS];

    for (long i = 0; i < NUM_THREADS; i++) {
        pthread_create(&threads[i], NULL, thread_func, (void*)i);
    }

    sleep(2);

    printf("\n[Main] All threads are waiting. Calling pthread_cond_broadcast!\n");
    printf("[Main] All %d threads will wake up at once (but mutex serializes them).\n\n", NUM_THREADS);

    pthread_mutex_lock(&mutex);
    condition_met = 1;
    pthread_cond_broadcast(&cond);
    pthread_mutex_unlock(&mutex);

    for (int i = 0; i < NUM_THREADS; i++) {
        pthread_join(threads[i], NULL);
    }

    pthread_mutex_destroy(&mutex);
    pthread_cond_destroy(&cond);

    printf("\n[Main] All %d threads finished.\n", NUM_THREADS);
    printf("[Main] Compare with 12-cond-simple.c where we used signal (one at a time).\n");
    return 0;
}
$ gcc -o broadcast 13-broadcast.c -lpthread
$ ./broadcast
Expected Outputclick Run to execute live
══════════════════════════════════════
  Broadcast vs Signal
══════════════════════════════════════

[Main] cond_signal:    wakes ONE waiting thread
[Main] cond_broadcast: wakes ALL waiting threads

[Main] Creating 20 threads, all will call cond_wait...

[Main] All threads are waiting. Calling pthread_cond_broadcast!
[Main] All 20 threads will wake up at once (but mutex serializes them).

[Thread  0] Woke up! Re-checking condition (mutex acquired)...
[Thread  0] Proceeding — condition is true.
[Thread  1] Woke up! Re-checking condition (mutex acquired)...
[Thread  1] Proceeding — condition is true.
[Thread  2] Woke up! Re-checking condition (mutex acquired)...
[Thread  2] Proceeding — condition is true.
[Thread  3] Woke up! Re-checking condition (mutex acquired)...
[Thread  3] Proceeding — condition is true.
[Thread  4] Woke up! Re-checking condition (mutex acquired)...
[Thread  4] Proceeding — condition is true.
[Thread  5] Woke up! Re-checking condition (mutex acquired)...
[Thread  5] Proceeding — condition is true.
[Thread  6] Woke up! Re-checking condition (mutex acquired)...
[Thread  6] Proceeding — condition is true.
[Thread  7] Woke up! Re-checking condition (mutex acquired)...
[Thread  7] Proceeding — condition is true.
[Thread  8] Woke up! Re-checking condition (mutex acquired)...
[Thread  8] Proceeding — condition is true.
[Thread  9] Woke up! Re-checking condition (mutex acquired)...
[Thread  9] Proceeding — condition is true.
[Thread 11] Woke up! Re-checking condition (mutex acquired)...
[Thread 11] Proceeding — condition is true.
[Thread 10] Woke up! Re-checking condition (mutex acquired)...
[Thread 10] Proceeding — condition is true.
[Thread 12] Woke up! Re-checking condition (mutex acquired)...
[Thread 13] Woke up! Re-checking condition (mutex acquired)...
[Thread 13] Proceeding — condition is true.
[Thread 14] Woke up! Re-checking condition (mutex acquired)...
[Thread 12] Proceeding — condition is true.
[Thread 14] Proceeding — condition is true.
[Thread 15] Woke up! Re-checking condition (mutex acquired)...
[Thread 15] Proceeding — condition is true.
[Thread 16] Woke up! Re-checking condition (mutex acquired)...
[Thread 16] Proceeding — condition is true.
[Thread 17] Woke up! Re-checking condition (mutex acquired)...
[Thread 17] Proceeding — condition is true.
[Thread 18] Woke up! Re-checking condition (mutex acquired)...
[Thread 18] Proceeding — condition is true.
[Thread 19] Woke up! Re-checking condition (mutex acquired)...
[Thread 19] Proceeding — condition is true.

[Main] All 20 threads finished.
[Main] Compare with 12-cond-simple.c where we used signal (one at a time).

Challenges

ChallengeLesson 14

Detect the deadlock

Two philosophers lock two forks in opposite order and wait forever. Make philosopher B give up after 2 seconds with pthread_mutex_timedlock(), print "deadlock detected" and release its fork. Click Edit, change the code, then Run — the site checks how it ended.

deadlock.c
/*
 * Challenge (Lesson 14): detect the deadlock
 *
 * Two threads take the same two mutexes in OPPOSITE order — the dining philosophers'
 * problem with two philosophers. Each grabs one lock and waits forever for the other.
 * Run it: it hangs (the site stops it after 10 seconds).
 *
 * Your task: thread B must not wait forever. Replace its second pthread_mutex_lock()
 * with pthread_mutex_timedlock() and a 2-second deadline. If it times out (ETIMEDOUT),
 * print "deadlock detected", release what it holds, and return.
 * Done when the program prints "deadlock detected" and exits on its own.
 */
#include <stdio.h>
#include <errno.h>
#include <time.h>
#include <pthread.h>
#include <unistd.h>

pthread_mutex_t fork_left = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t fork_right = PTHREAD_MUTEX_INITIALIZER;

void *philosopher_a(void *arg)
{
    pthread_mutex_lock(&fork_left);
    printf("[A] has the left fork, reaching for the right...\n");
    fflush(stdout);
    sleep(1);
    pthread_mutex_lock(&fork_right);   // waits for B
    printf("[A] eating\n");
    pthread_mutex_unlock(&fork_right);
    pthread_mutex_unlock(&fork_left);
    return NULL;
}

void *philosopher_b(void *arg)
{
    pthread_mutex_lock(&fork_right);
    printf("[B] has the right fork, reaching for the left...\n");
    fflush(stdout);
    sleep(1);

    // TODO: wait at most 2 seconds:
    //   struct timespec deadline; clock_gettime(CLOCK_REALTIME, &deadline); deadline.tv_sec += 2;
    //   if (pthread_mutex_timedlock(&fork_left, &deadline) == ETIMEDOUT) { ... }
    pthread_mutex_lock(&fork_left);    // waits for A — forever

    printf("[B] eating\n");
    pthread_mutex_unlock(&fork_left);
    pthread_mutex_unlock(&fork_right);
    return NULL;
}

int main(void)
{
    pthread_t a, b;
    pthread_create(&a, NULL, philosopher_a, NULL);
    pthread_create(&b, NULL, philosopher_b, NULL);
    pthread_join(b, NULL);
    pthread_join(a, NULL);
    printf("both philosophers finished\n");
    return 0;
}
$ gcc -Wall -o deadlock deadlock.c -lpthread
$ ./deadlock

Open Full Terminal

Get a Linux terminal with all 13 files from this lesson pre-loaded. Compile, run, and experiment freely.