This is one of the oldest synchronization primitives in the history ofcomputer science, invented by the early Dutch computer scientistEdsger W. Dijkstra (he usedP() andV() instead ofacquire() andrelease()).
A semaphore manages an internal counter which is decremented by eachacquire() call and incremented by eachrelease()call. The counter can never go below zero; whenacquire()finds that it is zero, it blocks, waiting until some other threadcallsrelease().
| [value]) |
1.| [blocking]) |
When invoked without arguments: if the internal counter is larger thanzero on entry, decrement it by one and return immediately. If it iszero on entry, block, waiting until some other thread has calledrelease() to make it larger than zero. This is done withproper interlocking so that if multipleacquire() calls areblocked,release() will wake exactly one of them up. Theimplementation may pick one at random, so the order in which blockedthreads are awakened should not be relied on. There is no returnvalue in this case.
When invoked withblocking set to true, do the same thing aswhen called without arguments, and return true.
When invoked withblocking set to false, do not block. If acall without an argument would block, return false immediately;otherwise, do the same thing as when called without arguments, andreturn true.
| ) |