Semaphore is a synchronization mechanism. In more words, semaphores are a technique for coordinating or synchronizing activities in which multiple processes compete for the same resources. There are 2 types of semaphores: Binary semaphores & Counting semaphores.
- Binary Semaphores: Only two states 0 & 1, i.e., locked/unlocked or available/unavailable, Mutex implementation.
- Counting Semaphores: Semaphores which allow arbitrary resource count called counting semaphores.
Here, we will see the POSIX style semaphore. POSIX semaphore calls are much simpler than the System V semaphore calls. However, System V semaphores are more widely available, particularly on older Unix-like systems. POSIX semaphores have been available on Linux systems post version 2.6 that use Glibc.
There are two types of POSIX semaphores: named & unnamed. The named semaphore(which internally implemented using shared memory) generally used between processes. As it creates shared memory system-wide & can use in multiple processes. But if you have threads only then, the unnamed semaphore will be the best choice.
Semaphore between processes example in C using POSIX-semaphore
|
|
sem_open() : Connects to, & optionally creates, a named semaphore( like
sem_init()`)sem_unlink() : Ends connection to an open semaphore & causes the semaphore to be removed when the last process closes it( like
sem_destroy()`sem_wait()
Wait for the semaphore to acquiresem_post()
Release semaphore
General pointers
- Semaphore’s internal implementation is like memory-mapped file(mmap)
- Two standards of semaphore mechanism
- POSIX-semaphore:
sem_init()
,sem_destroy()
,sem_wait()
,sem_post()
,sem_trywait()
,sem_getvalue()
,sem_open()
,sem_unlink()
- System-V-semaphore:
semget()
,semop()
,semctl()
- POSIX-semaphore: