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. But our focus would be on binary semaphore only. That too binary semaphore example between threads in C language specifically. If you are in search of semaphore between processes then see this.
- As its name suggest binary semaphore can have a value either 0 or 1.
- It means binary semaphore protect access to a SINGLE shared resource.
- So the internal counter of the semaphore can only take the values 1 or 0.
- When a resource is available, the process in charge set the semaphore to 1 else 0.
Example of Binary semaphore example between threads in C using POSIX-semaphore
| |
sem_init(): Initialize semaphoresem_destroy(): releases all resourcessem_wait(): Wait for the semaphore to acquiresem_post(): Release semaphoresem_trywait(): Only works when the caller does not have to waitsem_getvalue(): Reads the counter value of the semaphoresem_open(): Connects to, & optionally creates, a named semaphore( likesem_init())sem_unlink(): Ends connection to an open semaphore & causes the semaphore to be removed when the last process closes it( likesem_destroy())
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:
