C · 6 · Advanced / Job-Ready28 / 35 · 80%
POSIX Threads
pthread_create, mutexes, condition variables — real concurrency in C.
Examples: pthread_create, pthread_mutex_t
shortcuts: ← prev · → next · M mark
1
Create & Join
One process, many threads sharing the address space.
Example
example
#include <pthread.h>
void *worker(void *arg) {
int id = *(int*)arg;
printf("hi from %d\n", id);
return NULL;
}
int main(void) {
pthread_t t[3];
int ids[3] = {1, 2, 3};
for (int i = 0; i < 3; i++)
pthread_create(&t[i], NULL, worker, &ids[i]);
for (int i = 0; i < 3; i++)
pthread_join(t[i], NULL);
}main forks 3 workers
2
Mutex
Serialise access to shared data or you get a data race (UB).
Example
example
pthread_mutex_t m = PTHREAD_MUTEX_INITIALIZER;
int counter = 0;
void *inc(void *_) {
for (int i = 0; i < 100000; i++) {
pthread_mutex_lock(&m);
counter++;
pthread_mutex_unlock(&m);
}
return NULL;
}3
Condition Variables
Wait for a condition without busy-looping.
Example
example
pthread_mutex_t m = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t c = PTHREAD_COND_INITIALIZER;
int ready = 0;
// consumer
pthread_mutex_lock(&m);
while (!ready) pthread_cond_wait(&c, &m);
pthread_mutex_unlock(&m);
// producer
pthread_mutex_lock(&m);
ready = 1;
pthread_cond_signal(&c);
pthread_mutex_unlock(&m);WATCH OUT
Always use while(!cond), not if — spurious wakeups exist.
4
C11 Atomics
Lock-free counters and flags for hot paths.
Example
example
#include <stdatomic.h>
atomic_int hits = 0;
atomic_fetch_add(&hits, 1);
int v = atomic_load_explicit(&hits, memory_order_acquire);