Skip to content

semaphore

serhij.zolotukhin edited this page Dec 7, 2025 · 1 revision

THEORY

Semaphore
Counting Semaphore (англ. semaphore)
    Conceptually, a semaphore is a nonnegative integer count. Semaphores are typically
    used to coordinate access to resources, with the semaphore count initialized to the
    number of free resources
     
    - объект, ограничивающий количество потоков, которые могут войти в заданный участок кода.
    - это объект, над которым можно выполнить три операции.
    
    Инициализация семафора (задать начальное значение счётчика):
    Захват семафора (ждать пока счётчик станет больше 0, после этого уменьшить счётчик на единицу):
    Освобождение семафора (увеличить счётчик на единицу)
    
binary semaphore - is logically just like a mutex. 
    However, mutexes should be unlocked only by the thread that holds the lock.
    Because no notion exists of “the thread that holds the semaphore,” any thread can perform a sem_post(3RT) operation
Reader/writer semaphores

API

Pthread API semaphore
Semaphores might be usable by more than one process.

#include <semaphore.h>

// to atomically increment the semaphore
int sem_post(sem_t *sem); 

// to block the calling thread until the semaphore count becomes greater than zero, 
// then atomically decrement the count
int sem_wait(sem_t *sem);  

// to atomically decrement the count in the semaphore when the count is greater than zero.
int sem_trywait(sem_t *sem);         

My side bar

Clone this wiki locally