Multithreading with pthreads
Prerequisites: Hash tables
POSIX threads (pthread) let a C program run code concurrently on
multiple threads:
#include <pthread.h>
void *printNumbers(void *arg) {
for (int i = 0; i < 3; i++) {
printf("Thread: %d\n", i);
}
return NULL;
}
int main(void) {
pthread_t thread;
pthread_create(&thread, NULL, printNumbers, NULL);
pthread_join(thread, NULL); // wait for it to finish
return 0;
}
gcc program.c -o program -lpthread
A pthread_mutex_t protects shared data from being modified by two
threads at the same instant — exactly the same race-condition
problem Java's synchronized solves, just with an explicit
lock/unlock instead of a keyword:
pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
void increment(int *counter) {
pthread_mutex_lock(&lock);
(*counter)++;
pthread_mutex_unlock(&lock);
}
Common mistakes
- Forgetting
pthread_join— the main thread can exit (ending the whole process) before a spawned thread finishes its work.