Next: , Previous: msglimits, Up: Top



1.6 Semaphores

Each semaphore has a value >= 0. An id provides access to an array of nsems semaphores. Operations such as read, increment or decrement semaphores in a set are performed by the semop call which processes nsops operations at a time. Each operation is specified in a struct sembuf described below. The operations are applied only if all of them succeed.

If you do not have a need for such arrays, you are probably better off using the test_bit, set_bit and clear_bit bit-operations defined in <asm/bitops.h>.

Semaphore operations may also be qualified by a SEM_UNDO flag which results in the operation being undone when the process exits.

If a decrement cannot go through, a process will be put to sleep on a queue waiting for the semval to increase unless it specifies IPC_NOWAIT. A read operation can similarly result in a sleep on a queue waiting for semval to become 0. (Actually there are two queues per semaphore array).

A semaphore array is described by:

     struct semid_ds
       struct ipc_perm sem_perm;
       time_t          sem_otime;      /* last semop time */
       time_t          sem_ctime;      /* last change time */
       struct wait_queue *eventn;	  /* wait for a semval to increase */
       struct wait_queue *eventz;      /* wait for a semval to become 0 */
       struct sem_undo  *undo;         /* undo entries */
       ushort          sem_nsems;      /* no. of semaphores in array */

Each semaphore is described internally by :

     struct sem
       short   sempid;         /* pid of last semop() */
       ushort  semval;         /* current value */
       ushort  semncnt;        /* num procs awaiting increase in semval */
       ushort  semzcnt;        /* num procs awaiting semval = 0 */