Site Tools


semaphore

Table of Contents

Semaphore

Semaphore is a synchronization primitive. It's used to control thread execution in multithreaded environments.

A semaphore acts like an integer. An integer supports two well-known opeartions: increment i++ and decrement i--. A semaphore works in a similar way, except a semaphore cannot be decremented below zero. This is because semaphore takes action to protect its value against bankrupcy by taking hostage of threads that attempt to make it negative.

When a semaphore takes a thread in hostage, the thread stays blocked until it's rescued by another thread. A thread is rescued when a semaphore receives a payment in form of an increment. Then, instead of incrementing value, the semaphore releases one of its hostages. When all the hostage threads are released, further payments to the semaphore just increment the semaphore value as usual.

Illustration

// gcc main.c -o main && ./main
#include <stdio.h>
#include <semaphore.h>
 
int main()
{
    // Create semaphore with initial value 5
    sem_t sem;
    sem_init(&sem, 0, 5);
 
    // Count up to 100
    int i;
    for (i = 0; i < 100; i++) {
        sem_wait(&sem);
        printf("%d ", i);
        fflush(stdout);
        // sem_post(&sem)
    }
 
    // Destory semaphore
    sem_destroy(&sem);
    return 0;
 
}
semaphore.txt ยท Last modified: (external edit)