Semaphores

Semaphores, unlike message queues and pipes, are not used for exchanging data, but as a means of synchronizing operations among processes. A semaphore value is stored in the kernel and then set, read, and reset by sharing processes according to some defined scheme. A semaphore is created or an existing one is located with the semget() function. Typical uses include resource counting, file locking, and the serialization of shared memory.

A semaphore can have a single value or a set of values; each value can be binary (0 or 1) or a larger value, depending on the implementation. For each value in a set, the kernel keeps track of the process ID that did the last operation on that value, the number of processes waiting for the value to increase, and the number of processes waiting for the value to become 0.

If you define a semaphore set without any special flags, semop() processing obtains a kernel latch to serialize the semaphore set for each semop() or semctl() call. The more semaphores you define in the semaphore set, the higher the probability that you will experience contention on the semaphore latch. One alternative is to define multiple semaphore sets with fewer semaphores in each set. To get the least amount of latch contention, define a single semaphore in each semaphore set.

z/OS® has added the __IPC_BINSEM option to semget(). The __IPC_BINSEM option provides significant performance improvement on semop() processing. __IPC_BINSEM can only be specified if you use the semaphore as a binary semaphore and do not specify UNDO on any semop() calls. __IPC_BINSEM also allows semop() to use special hardware instructions to further reduce contention. With __IPC_BINSEM, you can define many semaphores in a semaphore set without impacting performance.