Table of Contents

Semaphore

Semaphore is a counter protecting access to shared resources, manipulated by atomic wait (decrements, blocks if negative) and signal (increments, wakes a blocked thread). A counting semaphore initialized to N allows up to N concurrent holders; a binary semaphore (N=1) is like a mutex but has no ownership, allowing any thread to signal.

Semaphores are more flexible than mutexes for signaling between threads, but lack ownership protection against bugs.

Example

This example shows semaphore use for limiting concurrent access to resources.

// compile: gcc -pthread -o sem sem.c
// run: ./sem
// description: semaphore limits concurrent resource access
 
#include <semaphore.h>
#include <pthread.h>
#include <stdio.h>
#include <unistd.h>
 
sem_t resource_pool;
 
void* use_resource(void* arg) {
    sem_wait(&resource_pool);
    printf("Thread using resource\n");
    sleep(1);
    printf("Thread done\n");
    sem_post(&resource_pool);
    return NULL;
}
 
int main() {
    sem_init(&resource_pool, 0, 2);  // allow 2 concurrent threads
 
    pthread_t t1, t2, t3;
    pthread_create(&t1, NULL, use_resource, NULL);
    pthread_create(&t2, NULL, use_resource, NULL);
    pthread_create(&t3, NULL, use_resource, NULL);
    pthread_join(t1, NULL);
    pthread_join(t2, NULL);
    pthread_join(t3, NULL);
 
    return 0;
}