Lesson 41 of 50 · c
POSIX Threads (`pthread`) – Advanced
Duration: 18 mins
On Unix‑like systems the POSIX thread library (pthread) provides a richer API.
Key components:
- Thread creation –
pthread_create(&tid, NULL, func, arg); - Joining –
pthread_join(tid, NULL); - Mutexes –
pthread_mutex_t, init withpthread_mutex_init. - Condition variables –
pthread_cond_tfor signalling. - Read‑write locks –
pthread_rwlock_t. - Thread attributes – stack size, detach state.
📚 Example: Producer‑Consumer with Condition Variable
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
#define BUF_SIZE 5
int buffer[BUF_SIZE];
int count = 0; // items in buffer
pthread_mutex_t mtx = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t not_full = PTHREAD_COND_INITIALIZER;
pthread_cond_t not_empty = PTHREAD_COND_INITIALIZER;
void *producer(void *arg) {
for (int i = 0; i < 20; ++i) {
pthread_mutex_lock(&mtx);
while (count == BUF_SIZE) pthread_cond_wait(¬_full, &mtx);
buffer[count++] = i;
printf("produced %d (count=%d)\n", i, count);
pthread_cond_signal(¬_empty);
pthread_mutex_unlock(&mtx);
usleep(100000);
}
return NULL;
}
void *consumer(void *arg) {
for (int i = 0; i < 20; ++i) {
pthread_mutex_lock(&mtx);
while (count == 0) pthread_cond_wait(¬_empty, &mtx);
int val = buffer[--count];
printf("consumed %d (count=%d)\n", val, count);
pthread_cond_signal(¬_full);
pthread_mutex_unlock(&mtx);
usleep(150000);
}
return NULL;
}
int main(void) {
pthread_t prod, cons;
pthread_create(&prod, NULL, producer, NULL);
pthread_create(&cons, NULL, consumer, NULL);
pthread_join(prod, NULL);
pthread_join(cons, NULL);
return 0;
}