What Is Wrong With PHP’s Semaphore Extension

Lack of a true Semaphore

sem_release() releases the semaphore if it is currently acquired by the calling process, otherwise a warning is generated.


By far the worst, this limitation makes a whole class of problems much more difficult to solve, and in fact means that PHP’s Semaphore extension, despite the name, is really a mutex (a semaphore with ownership, i.e., only the acquirer may release). Furthermore, it is inconsistent with the behavior of equivalent functions in other languages such as C and Python.

Please see phm\Lock\Semaphore for a kludgy workaround using mutexes, shared memory, and a message queue.

Undefined error handling

What happens if you sem_get() using a key that is already in use by a different type of resource, say, a System V shared memory segment? This is an issue because ftok() (the normal way of generating IPC keys for this stuff) is collision-prone, given a large enough filesystem.

Undefined behavior of sem_get()

[T]he documentation does not stipulate what will happen if the max_acquire paramter is varied upon successive invocations of the sem_get method. [S]o setting it to 100, then to 1 on 2 successive calls will have an undefined behavior.


This is avoidable, but it would be nice if this were fixed.

Cannot disable semaphore auto-releasing

If I write a program with a sem_get and auto_release=0, in case of shutdown, an other program should not be available to take the semaphore.

Bug #52701

A semaphore may be deleted when other processes are waiting to acquire it

sem_remove() should take the SYSVSEM_USAGE (see sysvsem.c) count into consideration when it is called. Only if this count is == 1 should the semaphore be removed. This will allow the last process that is using the semaphore to remove it from the system.

Bug #44109


The mantra among the PHP community seems to be “less bitchin’, more fixin’”, which is admirable. I do not wish to criticize or complain, but rather to document the need and hopefully encourage someone who has the background in C development to fix this (alas, I do not have this).

Written on December 8, 2012