Lesson 41 of 50
cPOSIX Threads (`pthread`) – Advanced
18 mins
Course progress82%
What you'll learn
Keep these ideas in mind as you work through the lesson.
Lesson 41 of 50
c18 mins
Keep these ideas in mind as you work through the lesson.
On Unix‑like systems the POSIX thread library (pthread) provides a richer API.
Key components:
pthread_create(&tid, NULL, func, arg);pthread_join(tid, NULL);pthread_mutex_t, init with pthread_mutex_init.pthread_cond_t for signalling.pthread_rwlock_t.#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)
", 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)
", 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;
}