Lesson 6 of 8
pthread Basics - Introduction to Multi-Threading (Optional)
POSIX threads (`pthread`) allow a process to run multiple concurrent threads sharing the same memory space. This is an optional advanced topic. The key concepts: `pthread_create`, `pthread_join`, `pthread_mutex_t` for mutual exclusion, and why shared state without synchronization causes data races. The Task Manager does not need threads, but this introduction prepares you for real-world concurrent C programs.
pthread Basics - Create, Join & Mutex
/* pthreads_intro.c - POSIX thread basics */
#define _POSIX_C_SOURCE 200809L
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>
/* ── Thread function signature - must return void* ───────── */
typedef struct {
int id;
int iterations;
int *shared_counter;
pthread_mutex_t *mutex;
} WorkerArgs;
void *worker(void *arg) {
WorkerArgs *a = (WorkerArgs *)arg;
for (int i = 0; i < a->iterations; i++) {
/* Without mutex: DATA RACE - counter corrupts silently */
pthread_mutex_lock(a->mutex);
(*a->shared_counter)++; /* critical section */
pthread_mutex_unlock(a->mutex);
}
printf("Worker %d done
", a->id);
return NULL; /* return value accessible via pthread_join */
}
#define NUM_THREADS 4
int main(void) {
pthread_t threads[NUM_THREADS];
pthread_mutex_t mutex;
int counter = 0;
WorkerArgs args[NUM_THREADS];
/* Initialise mutex */
if (pthread_mutex_init(&mutex, NULL) != 0) {
perror("pthread_mutex_init"); return 1;
}
/* Create threads */
for (int i = 0; i < NUM_THREADS; i++) {
args[i] = (WorkerArgs){ i, 10000, &counter, &mutex };
if (pthread_create(&threads[i], NULL, worker, &args[i]) != 0) {
perror("pthread_create"); return 1;
}
}
/* Wait for all threads to finish */
for (int i = 0; i < NUM_THREADS; i++) {
if (pthread_join(threads[i], NULL) != 0) {
perror("pthread_join");
}
}
pthread_mutex_destroy(&mutex);
/* Expected: NUM_THREADS * 10000 = 40000 */
printf("Counter = %d (expected %d)
", counter, NUM_THREADS * 10000);
/* ── Key pthread functions ──────────────────────────────
pthread_create(thread, attr, fn, arg) - create thread
pthread_join(thread, retval) - wait for thread
pthread_detach(thread) - don't join (fire-and-forget)
pthread_mutex_init/lock/unlock/destroy - mutual exclusion
pthread_cond_wait/signal/broadcast - condition variables
Build: gcc -Wall -std=c99 pthreads_intro.c -o pt -lpthread
↑ link pthread library */
return 0;
}Common Mistakes
- Not linking `-lpthread` - `pthread_create` fails at link time without `-lpthread`. On some systems, `-lpthread` also sets thread-safe errno. Always include it when using any pthread function.
- Stack-allocated args going out of scope - passing `&local_args` to a thread, then returning from the creating function before the thread reads the args. Use heap allocation or ensure the creating function blocks (joins) before returning.
- Forgetting `volatile` is NOT sufficient for thread safety - `volatile` prevents compiler optimisation but does NOT make an operation atomic or prevent CPU reordering. Always use `pthread_mutex_t` for shared mutable data, or `_Atomic` types from C11.
Tip
Tip
Practice pthread Basics Introduction to MultiThreading Optional in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.
POSIX threads enable concurrent execution while mutexes guard shared critical sections
Practice Task
Note
Practice Task - (1) Write a working example of pthread Basics Introduction to MultiThreading Optional from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.
Quick Quiz
Common Mistake
Warning
A common mistake with pthread Basics Introduction to MultiThreading Optional is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready c code.
Key Takeaways
- POSIX threads (`pthread`) allow a process to run multiple concurrent threads sharing the same memory space.
- Not linking `-lpthread` - `pthread_create` fails at link time without `-lpthread`. On some systems, `-lpthread` also sets thread-safe errno. Always include it when using any pthread function.
- Stack-allocated args going out of scope - passing `&local_args` to a thread, then returning from the creating function before the thread reads the args. Use heap allocation or ensure the creating function blocks (joins) before returning.
- Forgetting `volatile` is NOT sufficient for thread safety - `volatile` prevents compiler optimisation but does NOT make an operation atomic or prevent CPU reordering. Always use `pthread_mutex_t` for shared mutable data, or `_Atomic` types from C11.
Finished this lesson?