Semaphore
lastmod 2022-06-14created 2015-10-058 edits
A semaphore can be thought of as a simple counter that represents the state of a resource. This counter is a protected variable that users cannot access directly. The barrier around this variable is provided by none other than the kernel. Using a semaphore variable is simple. If the counter is greater than 0, the resource is available; if the counter is 0 or less, the resource is being used elsewhere. This simple mechanism helps synchronize multithreaded and multiprocess applications. Semaphores were devised by Edsger Dijkstra and are still used in today's operating systems for synchronization. Application developers use the same mechanism as well, and one of its most important aspects is inter-process communication.
Windows API
Unix C API
Comparison of Semaphore functions in Windows and Linux
Semaphores are used similarly on Windows and Linux.
On Linux, you can implement it similarly to Windows events; only the initial value needs to be set differently.
| Function | ||
| Create | CreateSemaphore | sem_init |
| Enter | sem_wait, sem_trywait | |
| Release | ReleaseSemaphore | sem_post |
| Destroy | CloseHandle | sem_destroy |