C
Summary - Pthreads
Combine create, mutex and cond to write a producer-consumer.
Combining producer-consumer
In this group you learned the core pthread tools: create with pthread_create, protect with pthread_mutex, notify with pthread_cond and wait with pthread_join. Together they build a concurrent system.
Now you will combine them into a producer-consumer: protect shared data with a mutex, synchronize producer and consumer with a condition variable. This pattern is the basis of queue systems.
Exercise Producer-consumer
Declare int items = 0;, pthread_mutex_t lock; and pthread_cond_t cond;. void *producer(void *arg): pthread_mutex_lock(&lock); items = 5; pthread_cond_signal(&cond); pthread_mutex_unlock(&lock);. void *consumer(void *arg): pthread_mutex_lock(&lock); while (items == 0) pthread_cond_wait(&cond, &lock); pthread_mutex_unlock(&lock);. Create both, join them and print printf("items=%d\n", items);.
Show example solution
#include <stdio.h>
#include <pthread.h>
int items = 0;
pthread_mutex_t lock;
pthread_cond_t cond;
void *producer(void *arg) {
pthread_mutex_lock(&lock);
items = 5;
pthread_cond_signal(&cond);
pthread_mutex_unlock(&lock);
return NULL;
}
void *consumer(void *arg) {
pthread_mutex_lock(&lock);
while (items == 0) {
pthread_cond_wait(&cond, &lock);
}
pthread_mutex_unlock(&lock);
return NULL;
}
int main(void) {
pthread_mutex_init(&lock, NULL);
pthread_cond_init(&cond, NULL);
pthread_t tp, tc;
pthread_create(&tc, NULL, consumer, NULL);
pthread_create(&tp, NULL, producer, NULL);
pthread_join(tp, NULL);
pthread_join(tc, NULL);
printf("items=%d\n", items);
return 0;
}
Next steps
You learned multithreading. In the next groups you will see network communication with socket programming.
Threads and sockets work together: a thread is created for each client. A mutex protects shared state, a condition variable guards the connection queue. The read and write calls are the same for descriptors and sockets. These foundations are the core of real-world servers.
Test yourself
-
Which trio builds the producer-consumer pattern?
- fork, exec, wait
- open, read, write
- signal, kill, raise
- mutex, cond, join
Show answer
mutex, cond, join — mutex protects, cond notifies, join waits.
-
Match pthread tools
- pthread_create
- Create thread
- pthread_mutex
- Protect shared data
- pthread_cond
- Notify
- pthread_join
- Wait and collect
Next lesson: What are sockets?