POSIX semaphores allow processes and threads to synchronize their actions.
A semaphore is an integer whose value is never allowed to fall below zero.
Two operations can be performed on semaphores:
increment the semaphore value by one
and decrement the semaphore value by one
If the value of a semaphore is currently zero, then a
operation will block until the value becomes greater than zero.
POSIX semaphores come in two forms: named semaphores and
A named semaphore is identified by a name of the form
Two processes can operate on the same named semaphore by passing
the same name to
function creates a new named semaphore or opens an existing
After the semaphore has been opened, it can be operated on using
When a process has finished using the semaphore, it can use
to close the semaphore.
When all processes have finished using the semaphore,
it can be removed from the system using
Unnamed semaphores (memory-based semaphores)
An unnamed semaphore does not have a name.
Instead the semaphore is placed in a region of memory that
is shared between multiple threads (a
or processes (a
A thread-shared semaphore is placed in an area of memory shared
between by the threads of a process, for example, a global variable.
A process-shared semaphore must be placed in a shared memory region
(e.g., a System V shared memory segment created using
or a POSIX shared memory object built created using
Before being used, an unnamed semaphore must be initialized using
It can then be operated on using
When the semaphore is no longer required,
and before the memory in which it is located is deallocated,
the semaphore should be destroyed using
The remainder of this section describes some specific details
of the Linux implementation of POSIX semaphores.
Prior to kernel 2.6, Linux only supported unnamed,
On a system with Linux 2.6 and a glibc that provides the NPTL
a complete implementation of POSIX semaphores is provided.
POSIX named semaphores have kernel persistence:
if not removed by
a semaphore will exist until the system is shut down.
Programs using the POSIX semaphores API must be compiled with
to link against the real-time library,
Accessing named semaphores via the file system
On Linux, named semaphores are created in a virtual file system,
normally mounted under
with names of the form
Since Linux 2.6.19, ACLs can be placed on files under this directory,
to control object permissions on a per-user and per-group basis.
System V semaphores
etc.) are an older semaphore API.
POSIX semaphores provide a simpler, and better designed interface than
System V semaphores;
on the other hand POSIX semaphores are less widely available
(especially on older systems) than System V semaphores.
An example of the use of various POSIX semaphore functions is shown in