CodeBlanks Logo Icon CodeBlanks

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.

Practice 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);.

Starter code

main.c
#include <stdio.h>
#include <pthread.h>

int items = 0;
pthread_mutex_t lock;
pthread_cond_t cond;

// Write producer and consumer
// Protect with mutex, sync with cond
// Print items

int main(void) {
    return 0;
}

Sample solution

main.c
#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;
}

Expected output

items=5

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.

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Which trio builds the producer-consumer pattern?

  • fork, exec, wait
  • open, read, write
  • signal, kill, raise
  • mutex, cond, join Correct answer

Explanation: mutex protects, cond notifies, join waits.

2 Match pthread tools

Term Meaning
pthread_create Create thread
pthread_mutex Protect shared data
pthread_cond Notify
pthread_join Wait and collect

All lessons in Advanced