Getting ready

The operation of a semaphore is based on two functions: acquire() and release(), as explained here:

  • Whenever a thread wants to access a given or a resource that is associated with a semaphore, it must invoke the acquire() operation, which decreases the internal variable of the semaphore and allows access to the resource if the value of this variable appears to be non-negative. If the value is negative, then the thread will be suspended and the release of the resource by another thread will be placed on hold.
  • Having finished using shared resources, the thread frees resources through the release() instruction. In this way, the internal variable of the semaphore is increased, allowing, for a waiting thread (if any), the opportunity to access the newly freed resource.

The semaphore is one of the oldest synchronization primitives in the history of computer science, invented by the early Dutch computer scientist Edsger W. Dijkstra.

The following example shows how to synchronize threads through a semaphore.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset