Lesson 12advancedThreads

POSIX Threads

Introduction to multi-threaded programming with pthreads. Covers thread creation, exit and return values, cleanup handlers, join, pthread_once, parallel partial sum, race conditions, and combining threads with other IPC mechanisms like FIFOs.

pthreadpthread_createpthread_jointhreadsrace-condition

Threads & Race Conditions

Multiple threads share the same memory. Without synchronization, concurrent access to shared data causes race conditions. A mutex ensures only one thread accesses the data at a time.

Without Mutexmain()pthread_create × 3Thread 0Thread 1Thread 2count++Expected: 3 Got: 1read 0read 0read 0⚠ RACE CONDITIONWith Mutexmain()pthread_create × 3Thread 0Thread 1Thread 2lockcount++Expected: 3 Got: 3 ✓🔒0→11→22→3waits...waits...✓ THREAD SAFEWithout protection:All threads read count=0 at the same timeAll write count=1 → 2 increments lostWith pthread_mutex_lock:Only one thread enters critical sectioncount goes 0→1→2→3 correctly
1

Creating Threads

The basics of pthread_create — spawning a thread with a function pointer and argument.

01-pthread_create.c
/*
 * 01-pthread_create.c — Creating your first thread
 *
 * Demonstrates: pthread_create() and pthread_exit()
 * Key concepts: Thread vs process, pthread_self(), shared address space
 * Compile: gcc -o thread1 01-pthread_create.c -lpthread
 * Run:     ./thread1
 *
 * Note: Both the main thread and the new thread run my_func concurrently.
 *       The interleaved output shows real parallelism.
 */

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>   // for pthread_create(), pthread_exit(), pthread_self()
#include <unistd.h>    // for getpid(), sleep()
#include <time.h>      // for time() (seeding rand)

// Thread function prototype
void* my_func(void *arg);

int main() {

    printf("\n");
    printf("══════════════════════════════════════\n");
    printf("  Creating your first thread\n");
    printf("══════════════════════════════════════\n\n");
    printf("\n");
    pthread_t thread_data;
    int a = 1;  // Value passed to thread
    int status;

    // Seed random number generator
    srand((unsigned) time(NULL));

    // Create a new thread running my_func, passing a pointer to 'a'
   /*
   pthread_create(&thread_data, NULL, my_func, (void *)&a)
&thread_data: The thread ID is stored here.
NULL: Using default thread attributes.
my_func: Function executed by the thread.
(void *)&a: The argument passed to the thread (a pointer to a).*/
    printf("[Main] Creating a new thread...\n");
    status = pthread_create(&thread_data, NULL, my_func, (void *) &a);
    if (status != 0) {
        fputs("[Main] ERROR: pthread_create failed!\n", stderr);
        exit(EXIT_FAILURE);
    }
    printf("[Main] Thread created (ID: %lu). Now main also calls my_func.\n", (unsigned long)thread_data);
    printf("[Main] Watch the interleaved output — both threads run concurrently!\n\n");

    // Main thread also runs my_func (simulate concurrency)
    my_func((void *)&a);
    puts("This line is never reached because both threads call pthread_exit");
    return EXIT_SUCCESS;
}

void* my_func(void *arg) {
    int i;
    int *val = (int *) arg;
    // Loop 5 times, printing process and thread info
    for (i = 0; i < 5; i++) {
        printf("[Thread %lu] PID=%d, iteration %d/5 (val=%d)\n",
               (unsigned long) pthread_self(), getpid(), i + 1, *val);
        sleep(rand() % 3); // Sleep for a random time between 0-2 seconds
    }
    // Exit the thread
    pthread_exit(NULL);
}
$ gcc -o pt_create 01-pthread_create.c -lpthread
$ ./pt_create
Expected Outputclick Run to execute live
══════════════════════════════════════
  Creating your first thread
══════════════════════════════════════


[Main] Creating a new thread...
[Main] Thread created (ID: 137964217613112). Now main also calls my_func.
[Main] Watch the interleaved output — both threads run concurrently!

[Thread 137964218329896] PID=2472, iteration 1/5 (val=1)
[Thread 137964217613112] PID=2472, iteration 1/5 (val=1)
[Thread 137964217613112] PID=2472, iteration 2/5 (val=1)
[Thread 137964217613112] PID=2472, iteration 3/5 (val=1)
[Thread 137964218329896] PID=2472, iteration 2/5 (val=1)
[Thread 137964217613112] PID=2472, iteration 4/5 (val=1)
[Thread 137964218329896] PID=2472, iteration 3/5 (val=1)
[Thread 137964217613112] PID=2472, iteration 5/5 (val=1)
[Thread 137964218329896] PID=2472, iteration 4/5 (val=1)
[Thread 137964218329896] PID=2472, iteration 5/5 (val=1)
2

Thread Exit with Return Values

Using pthread_exit to return a value from a thread, collected by pthread_join.

02-pthread_exit.c
$ gcc -o pt_exit 02-pthread_exit.c -lpthread
$ ./pt_exit
Expected Outputclick Run to execute live
══════════════════════════════════════
  pthread_exit with return values
══════════════════════════════════════


[Main] Input array: 17 38 79 3879 

[Main] Creating thread to negate all values...
[Main] Waiting for thread to finish (pthread_join)...
[Thread] Received input: 17 38 79 3879 
[Thread] Negating each value...

[Main] Thread finished! Returned array: -17 -38 -79 -3879 
[Main] The thread allocated memory, returned it via pthread_exit, and main read it via pthread_join.
3

Cleanup Handlers

Registering cleanup handlers with pthread_cleanup_push/pop — they run when a thread is cancelled or exits.

03-pthread_cleanup.c
$ gcc -o pt_cleanup 03-pthread_cleanup.c -lpthread
$ ./pt_cleanup
Expected Outputclick Run to execute live
══════════════════════════════════════
  pthread_cleanup — Cleanup Handlers
══════════════════════════════════════

[Main] Cleanup handlers are functions that run automatically
       when a thread is cancelled or calls pthread_exit.

[Main] Creating secondary thread...
[Thread] Started. Registering cleanup handlers...
[Thread] Cleanup handlers registered (2 handlers on stack).
[Thread] Running... (will be cancelled by main after ~2 seconds)

[Thread] Still running...
[Thread] Still running...

[Main] Cancelling the thread with pthread_cancel()...
[Main] This should trigger the cleanup handlers.
[Thread] Still running...
Segmentation fault         (core dumped) ./pt_cleanup
Sometimes crashes on purpose: the thread may return from inside pthread_cleanup_push/pop (1 in 10 per second) — undefined behaviour, which musl punishes with SIGSEGV
4

Joining Threads

Waiting for threads to complete with pthread_join and retrieving their return values.

04-pthread_join.c
$ gcc -o pt_join 04-pthread_join.c -lpthread
$ ./pt_join
Expected Outputclick Run to execute live
[Main] Creating 5 threads, each will increment a shared counter 10 times.
[Main] NO mutex is used — watch for the race condition!

[Main] Created thread 0
[Main] Created thread 1
[Thread 1] counter++ → 1 (NO mutex — race condition possible!)
[Main] Created thread 2
[Main] Created thread 3
[Main] Created thread 4
[Thread 2] counter++ → 3 (NO mutex — race condition possible!)
[Thread 3] counter++ → 2 (NO mutex — race condition possible!)
[Thread 4] counter++ → 4 (NO mutex — race condition possible!)

[Main] All threads created. Calling pthread_join on each...

[Thread 2] counter++ → 5 (NO mutex — race condition possible!)
[Thread 0] counter++ → 6 (NO mutex — race condition possible!)
[Thread 2] counter++ → 7 (NO mutex — race condition possible!)
[Thread 0] counter++ → 8 (NO mutex — race condition possible!)
[Thread 0] counter++ → 9 (NO mutex — race condition possible!)
[Thread 4] counter++ → 10 (NO mutex — race condition possible!)
[Thread 2] counter++ → 11 (NO mutex — race condition possible!)
[Thread 4] counter++ → 12 (NO mutex — race condition possible!)
[Thread 0] counter++ → 13 (NO mutex — race condition possible!)
[Thread 0] counter++ → 14 (NO mutex — race condition possible!)
[Thread 0] counter++ → 15 (NO mutex — race condition possible!)
[Thread 0] counter++ → 16 (NO mutex — race condition possible!)
[Thread 1] counter++ → 17 (NO mutex — race condition possible!)
[Thread 1] counter++ → 18 (NO mutex — race condition possible!)
[Thread 1] counter++ → 19 (NO mutex — race condition possible!)
[Thread 3] counter++ → 20 (NO mutex — race condition possible!)
[Thread 3] counter++ → 21 (NO mutex — race condition possible!)
[Thread 3] counter++ → 22 (NO mutex — race condition possible!)
[Thread 2] counter++ → 23 (NO mutex — race condition possible!)
[Thread 4] counter++ → 24 (NO mutex — race condition possible!)
[Thread 4] counter++ → 25 (NO mutex — race condition possible!)
[Thread 0] counter++ → 26 (NO mutex — race condition possible!)
[Thread 1] counter++ → 27 (NO mutex — race condition possible!)
[Thread 1] counter++ → 28 (NO mutex — race condition possible!)
[Thread 1] counter++ → 29 (NO mutex — race condition possible!)
[Thread 3] counter++ → 30 (NO mutex — race condition possible!)
[Thread 3] counter++ → 31 (NO mutex — race condition possible!)
[Thread 3] counter++ → 32 (NO mutex — race condition possible!)
[Thread 2] counter++ → 33 (NO mutex — race condition possible!)
[Thread 4] counter++ → 34 (NO mutex — race condition possible!)
[Thread 0] counter++ → 35 (NO mutex — race condition possible!)
[Thread 4] counter++ → 36 (NO mutex — race condition possible!)
[Thread 1] counter++ → 37 (NO mutex — race condition possible!)
[Thread 1] counter++ → 38 (NO mutex — race condition possible!)
[Thread 1] counter++ → 39 (NO mutex — race condition possible!)
[Thread 3] counter++ → 40 (NO mutex — race condition possible!)
[Thread 2] counter++ → 41 (NO mutex — race condition possible!)
[Thread 0] counter++ → 42 (NO mutex — race condition possible!)
[Thread 4] counter++ → 43 (NO mutex — race condition possible!)
[Thread 3] counter++ → 44 (NO mutex — race condition possible!)
[Thread 2] counter++ → 45 (NO mutex — race condition possible!)
[Thread 4] counter++ → 46 (NO mutex — race condition possible!)
[Thread 2] counter++ → 47 (NO mutex — race condition possible!)
[Thread 3] counter++ → 48 (NO mutex — race condition possible!)
[Thread 4] counter++ → 49 (NO mutex — race condition possible!)
[Thread 2] counter++ → 50 (NO mutex — race condition possible!)

══════════════════════════════════════
  Results
══════════════════════════════════════
  Expected counter: 50 (5 threads × 10 increments)
  Actual counter:   50 ← correct (got lucky this time)
5

Ping-Pong (Busy Waiting)

Two threads taking turns printing "ping" and "pong" using a shared flag — a deliberate busy-wait anti-pattern.

05-pthread_ping_pong.c
/*
 * 05-pthread_ping_pong.c — Ping-pong between threads using busy waiting
 *
 * Key concepts: Shared flag, busy waiting (spin loop), thread coordination
 * Compile: gcc -o pingpong 05-pthread_ping_pong.c -lpthread
 * Run:     ./prog
 */
// File: pthread_pingpong.c
// Compile with: gcc -Wall -pthread pthread_pingpong.c -o pthread_pingpong

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

// Global variable to indicate whose turn it is (0 or 1)
volatile int turn = 0;

// Thread function prototype
void* pingpong(void *arg);

int main() {

    printf("\n");
    printf("══════════════════════════════════════\n");
    printf("  Ping-pong between threads using busy waiting\n");
    printf("══════════════════════════════════════\n\n");
    printf("\n");
    pthread_t threads[2];
    int ids[2] = {0, 1};
    int status;

    // Seed random number generator.
    srand((unsigned) time(NULL));

    printf("[Main] Two threads take turns printing — coordinated via a shared 'turn' flag.\n");
    printf("[Main] Thread 0 = Ping, Thread 1 = Pong. Each waits in a spin loop (busy wait).\n");
    printf("[Main] Note: busy waiting wastes CPU! Better approaches: mutex + cond_wait (lesson 13).\n\n");

    for (int i = 0; i < 2; i++) {
        status = pthread_create(&threads[i], NULL, pingpong, &ids[i]);
        if (status != 0) {
            fprintf(stderr, "[Main] ERROR: pthread_create failed (rc=%d)\n", status);
            exit(EXIT_FAILURE);
        }
    }

    for (int i = 0; i < 2; i++) {
        pthread_join(threads[i], NULL);
    }
    printf("\n[Main] Ping-Pong complete — 5 rounds each, perfectly alternating.\n");
    return EXIT_SUCCESS;
}

void* pingpong(void *arg) {
    int id = *((int *) arg);
    // Each thread will print its message 5 times.
    for (int round = 0; round < 5; round++) {
        // Busy wait until it is this thread's turn.
        while (turn != id) {
            ; // Do nothing
        }

        // Print message: "Ping" or "Pong"
        if (id == 0)
            printf("[Thread 0] Ping! (round %d)\n", round + 1);
        else
            printf("[Thread 1]   Pong! (round %d)\n", round + 1);

        // Let the other thread proceed.
        turn = 1 - id;
        sleep(1); // Simulate work
    }
    pthread_exit(NULL);
}
$ gcc -o pt_pingpong 05-pthread_ping_pong.c -lpthread
$ ./pt_pingpong
Expected Outputclick Run to execute live
══════════════════════════════════════
  Ping-pong between threads using busy waiting
══════════════════════════════════════


[Main] Two threads take turns printing — coordinated via a shared 'turn' flag.
[Main] Thread 0 = Ping, Thread 1 = Pong. Each waits in a spin loop (busy wait).
[Main] Note: busy waiting wastes CPU! Better approaches: mutex + cond_wait (lesson 13).

[Thread 0] Ping! (round 1)
[Thread 1]   Pong! (round 1)
[Thread 0] Ping! (round 2)
[Thread 1]   Pong! (round 2)
[Thread 0] Ping! (round 3)
[Thread 1]   Pong! (round 3)
[Thread 0] Ping! (round 4)
[Thread 1]   Pong! (round 4)
[Thread 0] Ping! (round 5)
[Thread 1]   Pong! (round 5)

[Main] Ping-Pong complete — 5 rounds each, perfectly alternating.
6

pthread_once

Ensuring an initialization function runs exactly once across all threads using pthread_once.

06-pthread-once.c
/*
 * 06-pthread-once.c — pthread_once — initialization that runs exactly once
 *
 * Key concepts: pthread_once_t, thread-safe one-time init
 * Compile: gcc -o once 06-pthread-once.c -lpthread
 * Run:     ./prog
 */
// File: pthread_once_example.c
// Compile with: gcc -Wall -pthread pthread_once_example.c -o pthread_once_example

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

void* my_func(void *arg);
void init(); // This function will be called only once

int *arr;
int counter = 0;
pthread_once_t once_control = PTHREAD_ONCE_INIT;

int main() {

    printf("\n");
    printf("══════════════════════════════════════\n");
    printf("  pthread_once\n");
    printf("══════════════════════════════════════\n\n");
    printf("\n");
    pthread_t threads[5];
    int i, status;

    printf("[Main] Creating 5 threads. Each calls pthread_once() to ensure init() runs ONCE.\n");
    printf("[Main] Only the FIRST thread to call pthread_once will execute init().\n\n");

    for (i = 0; i < 5; i++) {
        status = pthread_create(&threads[i], NULL, my_func, NULL);
        if (status != 0) {
            fprintf(stderr, "[Main] ERROR: pthread_create failed\n");
            exit(EXIT_FAILURE);
        }
        printf("[Main] Created thread %d\n", i);
    }

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

    printf("\n[Main] All threads finished. Shared array contents: ");
    for (i = 0; i < counter; i++) {
        printf("%d ", arr[i]);
    }
    printf("\n[Main] init() ran exactly once, even though 5 threads called pthread_once.\n");
    free(arr);
    return EXIT_SUCCESS;
}

void* my_func(void *arg) {
    // Ensure that init() is called exactly once.
    pthread_once(&once_control, init);
    // For demonstration, each thread adds a random number to the shared array.
    arr[counter++] = rand() % 10;
    pthread_exit(NULL);
}

void init() {
    printf("  [init()] This runs EXACTLY ONCE — allocating shared array.\n\n");
    srand(time(NULL));
    arr = (int *) malloc(5 * sizeof(int));
    if (!arr) {
        perror("malloc() failed");
        exit(EXIT_FAILURE);
    }
}
$ gcc -o pt_once 06-pthread-once.c -lpthread
$ ./pt_once
Expected Outputclick Run to execute live
══════════════════════════════════════
  pthread_once
══════════════════════════════════════


[Main] Creating 5 threads. Each calls pthread_once() to ensure init() runs ONCE.
[Main] Only the FIRST thread to call pthread_once will execute init().

[Main] Created thread 0
[Main] Created thread 1
[Main] Created thread 2
[Main] Created thread 3
[Main] Created thread 4
  [init()] This runs EXACTLY ONCE — allocating shared array.


[Main] All threads finished. Shared array contents: 3 9 5 3 2 
[Main] init() ran exactly once, even though 5 threads called pthread_once.
7

Parallel Partial Sum

Splitting an array across threads, each computing a partial sum, then combining results — a real parallelism speedup.

07-partial-sum.c
$ gcc -o pt_sum 07-partial-sum.c -lpthread
$ ./pt_sum
Expected Outputclick Run to execute live
Initializing array with values: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20

[Main] Splitting into 4 threads (5 elements each)...

[Thread 1] Processing indices 5..9: 6 + 7 + 8 + 9 + 10 = 40
[Thread 3] Processing indices 15..19: 16 + 17 + 18 + 19 + 20 = 90
[Thread 2] Processing indices 10..14: 11 + 12 + 13 + 14 + 15 = 65
[Thread 0] Processing indices 0..4: 1 + 2 + 3 + 4 + 5 = 15
[Main] Thread 0 finished — partial sum = 15
[Main] Thread 1 finished — partial sum = 40
[Main] Thread 2 finished — partial sum = 65
[Main] Thread 3 finished — partial sum = 90

══════════════════════════════════════
  Total sum = 210  (sum of 1..20 = 20 × 21 / 2 = 210 ✓)
══════════════════════════════════════
8

Main Exits Before Threads

What happens when main() returns while threads are still running — demonstrating the need for join or pthread_exit in main.

08-pthread-exit.c
/*
 * 08-pthread-exit.c — Main thread exits early, worker threads continue
 *
 * Key concepts: pthread_exit from main, process stays alive for threads
 * Compile: gcc -o early_exit 08-pthread-exit.c -lpthread
 * Run:     ./prog
 */
// File: main_exits_but_threads_continue.c
// Compile with: gcc -Wall -pthread main_exits_but_threads_continue.c -o main_exits_but_threads_continue

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

// Thread function: prints its ID and iteration count.
void* thread_func(void *arg) {
    int id = *((int *) arg);
    for (int i = 0; i < 10; i++) {
        printf("[Thread %d] Iteration %d/10 — still running after main exited!\n", id, i + 1);
        sleep(1);
    }
    printf("[Thread %d] Finished all 10 iterations.\n", id);
    pthread_exit(NULL);
}

int main() {

    printf("\n");
    printf("══════════════════════════════════════\n");
    printf("  Main thread exits early, worker threads continue\n");
    printf("══════════════════════════════════════\n\n");
    printf("\n");
    pthread_t threads[3];
    int thread_ids[3] = {1, 2, 3};
    
    printf("[Main] Key concept: if main calls return/exit, ALL threads die.\n");
    printf("[Main] But if main calls pthread_exit, the process stays alive for worker threads!\n\n");

    for (int i = 0; i < 3; i++) {
        if (pthread_create(&threads[i], NULL, thread_func, (void *) &thread_ids[i]) != 0) {
            perror("[Main] ERROR: pthread_create failed");
            exit(EXIT_FAILURE);
        }
        printf("[Main] Created thread %d\n", thread_ids[i]);
    }

    printf("\n[Main] Calling pthread_exit() NOW — main thread stops, but threads keep running!\n");
    printf("[Main] Watch: the thread output continues even though main is gone.\n\n");
    
    // Instead of exiting normally (which would end the process and kill all threads),
    // the main thread calls pthread_exit. This causes the main thread to finish its work
    // while keeping the process alive until all non-detached threads complete.
    pthread_exit(NULL);
    
    // Note: Any code after pthread_exit() will not be executed.
    return EXIT_SUCCESS;
}
$ gcc -o pt_exit2 08-pthread-exit.c -lpthread
$ ./pt_exit2
Expected Outputclick Run to execute live
══════════════════════════════════════
  Main thread exits early, worker threads continue
══════════════════════════════════════


[Main] Key concept: if main calls return/exit, ALL threads die.
[Main] But if main calls pthread_exit, the process stays alive for worker threads!

[Main] Created thread 1
[Thread 1] Iteration 1/10 — still running after main exited!
[Main] Created thread 2
[Thread 2] Iteration 1/10 — still running after main exited!
[Main] Created thread 3

[Main] Calling pthread_exit() NOW — main thread stops, but threads keep running!
[Main] Watch: the thread output continues even though main is gone.

[Thread 3] Iteration 1/10 — still running after main exited!
[Thread 1] Iteration 2/10 — still running after main exited!
[Thread 2] Iteration 2/10 — still running after main exited!
[Thread 3] Iteration 2/10 — still running after main exited!
[Thread 1] Iteration 3/10 — still running after main exited!
[Thread 2] Iteration 3/10 — still running after main exited!
[Thread 3] Iteration 3/10 — still running after main exited!
[Thread 1] Iteration 4/10 — still running after main exited!
[Thread 2] Iteration 4/10 — still running after main exited!
[Thread 3] Iteration 4/10 — still running after main exited!
[Thread 1] Iteration 5/10 — still running after main exited!
[Thread 3] Iteration 5/10 — still running after main exited!
[Thread 2] Iteration 5/10 — still running after main exited!
[Thread 1] Iteration 6/10 — still running after main exited!
[Thread 3] Iteration 6/10 — still running after main exited!
[Thread 2] Iteration 6/10 — still running after main exited!
[Thread 1] Iteration 7/10 — still running after main exited!
[Thread 3] Iteration 7/10 — still running after main exited!
[Thread 2] Iteration 7/10 — still running after main exited!
[Thread 1] Iteration 8/10 — still running after main exited!
[Thread 3] Iteration 8/10 — still running after main exited!
[Thread 2] Iteration 8/10 — still running after main exited!
[Thread 1] Iteration 9/10 — still running after main exited!
[Thread 3] Iteration 9/10 — still running after main exited!
[Thread 2] Iteration 9/10 — still running after main exited!
[Thread 1] Iteration 10/10 — still running after main exited!
[Thread 3] Iteration 10/10 — still running after main exited!
[Thread 2] Iteration 10/10 — still running after main exited!
[Thread 1] Finished all 10 iterations.
[Thread 3] Finished all 10 iterations.
[Thread 2] Finished all 10 iterations.
Runs until stopped — stops automatically after 15s
9

Countdown Race Condition

Multiple threads decrementing a shared counter without synchronization — observe the race condition in action.

09-countdown-race.c
$ gcc -o pt_race 09-countdown-race.c -lpthread
$ ./pt_race
Expected Outputclick Run to execute live
══════════════════════════════════════
  Thread race: first to count down to zero wins
══════════════════════════════════════


[Main] Each thread gets a random countdown (5-10 seconds). First to 0 wins!
[Main] WARNING: the winner check has NO mutex — a race condition on purpose.

[Main] Thread 0 starts with countdown = 5
[Main] Thread 1 starts with countdown = 9
[Main] Thread 2 starts with countdown = 10

[Main] Race started! Main thread calling pthread_exit (threads keep running).

[Thread 2] Counting down: 9 remaining
[Thread 0] Counting down: 4 remaining
[Thread 1] Counting down: 8 remaining
[Thread 2] Counting down: 8 remaining
[Thread 0] Counting down: 3 remaining
[Thread 1] Counting down: 7 remaining
[Thread 2] Counting down: 7 remaining
[Thread 0] Counting down: 2 remaining
[Thread 1] Counting down: 6 remaining
[Thread 2] Counting down: 6 remaining
[Thread 0] Counting down: 1 remaining
[Thread 1] Counting down: 5 remaining
[Thread 2] Counting down: 5 remaining
[Thread 0] Counting down: 0 remaining
[Thread 0] *** I WON THE RACE! *** (race condition: no mutex!)
[Thread 1] Counting down: 4 remaining
[Thread 1] Thread 0 already won — I'm exiting.
[Thread 1] Cleanup handler called — releasing resources.
[Thread 2] Counting down: 4 remaining
[Thread 2] Thread 0 already won — I'm exiting.
[Thread 2] Cleanup handler called — releasing resources.
10

Async Chat Simulator

A threaded chat simulator where one thread reads input and another displays messages asynchronously.

10-async-chat.c
$ gcc -o pt_chat 10-async-chat.c -lpthread
$ ./pt_chat
Expected Outputclick Run to execute live
══════════════════════════════════════
  Async chat simulator with threads
══════════════════════════════════════


[Main] Starting 3 chat participants, each will post 5 messages.
[Main] WARNING: no mutex on shared log — messages may get lost or corrupted!

[Main] All participants started. Main exits, chat continues...

[Participant 0] Posted message 1/5: "P0 msg 0" (log position: 0)
[Participant 1] Posted message 1/5: "P1 msg 0" (log position: 1)
[Participant 1] Posted message 2/5: "P1 msg 1" (log position: 2)
[Participant 2] Posted message 1/5: "P2 msg 0" (log position: 3)
[Participant 0] Posted message 2/5: "P0 msg 1" (log position: 4)
[Participant 1] Posted message 3/5: "P1 msg 2" (log position: 5)
[Participant 1] Posted message 4/5: "P1 msg 3" (log position: 6)
[Participant 2] Posted message 2/5: "P2 msg 1" (log position: 7)
[Participant 0] Posted message 3/5: "P0 msg 2" (log position: 8)
[Participant 0] Posted message 4/5: "P0 msg 3" (log position: 9)
[Participant 2] Posted message 3/5: "P2 msg 2" (log position: 10)
[Participant 1] Posted message 5/5: "P1 msg 4" (log position: 11)
[Participant 0] Posted message 5/5: "P0 msg 4" (log position: 12)
[Participant 2] Posted message 4/5: "P2 msg 3" (log position: 13)
[Participant 2] Posted message 5/5: "P2 msg 4" (log position: 14)
Runs until stopped — stops automatically after 25s
11

Threads + FIFO

Combining pthreads with named pipes (FIFO) — one thread reads from a FIFO while the main thread handles other work.

11-pthreads-fifo.c
$ gcc -o pt_fifo 11-pthreads-fifo.c -lpthread
$ ./pt_fifo
Expected Outputclick Run to execute live
══════════════════════════════════════
  Threads + FIFO Communication
══════════════════════════════════════

[Main] Two threads communicate via named pipes (FIFOs).
[Main] Writer sends 10 messages, Reader acknowledges each.

[Writer] Sent "Message 0 from writer"
[Reader] Got: "Message 0 from writer"
[Reader] Sent ACK: "Acknowledged: Message 0 from writer"
[Writer] Got ACK: "Acknowledged: Message 0 from writer"
[Writer] Sent "Message 1 from writer"
[Reader] Got: "Message 1 from writer"
[Writer] Got ACK: "Acknowledged: Message 1 from writer"
[Writer] Sent "Message 2 from writer"
[Reader] Sent ACK: "Acknowledged: Message 1 from writer"
[Reader] Got: "Message 2 from writer"
[Reader] Sent ACK: "Acknowledged: Message 2 from writer"
[Writer] Got ACK: "Acknowledged: Message 2 from writer"
[Reader] Got: "Message 3 from writer"
[Reader] Sent ACK: "Acknowledged: Message 3 from writer"
[Writer] Sent "Message 3 from writer"
[Writer] Got ACK: "Acknowledged: Message 3 from writer"
[Reader] Got: "Message 4 from writer"
[Reader] Sent ACK: "Acknowledged: Message 4 from writer"
[Writer] Sent "Message 4 from writer"
[Writer] Got ACK: "Acknowledged: Message 4 from writer"
[Reader] Got: "Message 5 from writer"
[Reader] Sent ACK: "Acknowledged: Message 5 from writer"
[Writer] Sent "Message 5 from writer"
[Writer] Got ACK: "Acknowledged: Message 5 from writer"
[Writer] Sent "Message 6 from writer"
[Reader] Got: "Message 6 from writer"
[Writer] Got ACK: "Acknowledged: Message 6 from writer"
[Writer] Sent "Message 7 from writer"
[Reader] Sent ACK: "Acknowledged: Message 6 from writer"
[Reader] Got: "Message 7 from writer"
[Writer] Got ACK: "Acknowledged: Message 7 from writer"
[Writer] Sent "Message 8 from writer"
[Reader] Sent ACK: "Acknowledged: Message 7 from writer"
[Reader] Got: "Message 8 from writer"
[Writer] Got ACK: "Acknowledged: Message 8 from writer"
[Writer] Sent "Message 9 from writer"
[Reader] Sent ACK: "Acknowledged: Message 8 from writer"
[Reader] Got: "Message 9 from writer"
[Writer] Got ACK: "Acknowledged: Message 9 from writer"
[Reader] Sent ACK: "Acknowledged: Message 9 from writer"

Open Full Terminal

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