Skip to main content
Brave Programmer Logo

BraveProgrammer

BraveProgrammer

HomeProjectsBlogsCoursesLessonsAbout

Site footer

BraveProgrammer

Free coding courses, practical tutorials, and real projects from BraveProgrammer. Learn web development with React, Next.js, and TypeScript.

Navigation

  • Home
  • Projects
  • Blogs
  • Courses

Resources

  • About
  • Lessons

© 2026 BraveProgrammer. All rights reserved.

  1. Courses
  2. /
  3. C Programming Fundamentals

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 with pthread_mutex_init.
  • Condition variables – pthread_cond_t for 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(&not_full, &mtx);
        buffer[count++] = i;
        printf("produced %d (count=%d)\n", i, count);
        pthread_cond_signal(&not_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(&not_empty, &mtx);
        int val = buffer[--count];
        printf("consumed %d (count=%d)\n", val, count);
        pthread_cond_signal(&not_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;
}
Previous: Multithreading with `<threads.h>` (C11)Next: Signal Handling (`signal.h`)