O'Reilly logo

Patterns for Parallel Software Design by Jorge Luis Ortega-Arjona

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

5.1. 5.1 Semaphore

A semaphore is a synchronization mechanism that allows two or more concurrent, parallel or distributed software components, executing on a shared memory parallel platform, to block (wait) for an event to occur. It is intended to solve the mutual exclusion problem, in which more than one software components should not be allowed to manipulate a shared variable at the same time [Dij68] [And91] [Bac93] [KSS96] [Har98] [And00].

5.1.1. Example

The C programming language has been often extended to cover aspects of concurrent, parallel and distributed programming. Semaphores have been implemented in C using an extended library from POSIX and commonly are used for implementing concurrent programs, particularly operating systems.

For this example, consider a pipe component based on the Shared Variable Pipe pattern from Section 4.1, implemented using Java-like monitors. In the current example, the objective is to use semaphores in C as the synchronization mechanism. To use semaphores in C, some details about POSIX semaphores must be considered, as defined in the file <semaphore.h> [KSS96] [And00]:

  • sem_t* sem_open(cont char *name): Returns a pointer to a semaphore.

  • int sem_close(sem_t *semaphore): Destroys the pointer to a semaphore.

  • int sem_init(sem_t* semaphore, int pshared, unsigned int count): Sets an integer initial count value to the semaphore. If pshared is not zero, the semaphore may be used by more than one thread.

  • int sem_wait(sem_t* semaphore): Decrements the ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required