sem_acquire

(PHP 4, PHP 5, PHP 7)

sem_acquire — Acquire a semaphore

Description

boolsem_acquire
( resource$sem_identifier
[, bool$nowait = false
] )

sem_acquire() by default blocks (if necessary) until the
semaphore can be acquired. A process attempting to acquire a semaphore which
it has already acquired will block forever if acquiring the semaphore would
cause its maximum number of semaphore to be exceeded.

After processing a request, any semaphores acquired by the process but not
explicitly released will be released automatically and a warning will be
generated.

Changelog

See Also

User Contributed Notes 6 notes

sem_acquire() is blocking, meaning that subsequent calls with the same semaphore will block indefinitely until the semaphore is released. This ensures serialization, but it is not very practical if all you want to do is check if you should proceed or not. Unfortunately, PHP does not yet support any method of querying the state of a semaphore in a non-blocking manner.

It may seem possible to put together such a mechanism by hand, using shared memory (shm_ functions). However, be warned that it is not trivial and ultimately non-productive. You cannot, for example, simply pick a shared mem var, store the semaphore key and query it. Such an operation would be non-transactional and non-atomic ie. it is possible for two or more parallel processes to manage to read "not locked" from the shared mem var before one of them manages to mark it "locked". You would have to use a (blocking) semaphore to serialize access to the shared mem var, thus recreating the very problem you are trying to solve.

In other words, if non-blocking queries are crucial to you, you need to either request that this issue be solved by the PHP designers, or pick another mechanism to do your locking, one that already has this feature.

On the Apache webserver, many PHP requests will be executed within the same process space because it is multithreaded. However, any semaphores got and acquired by a script and not released and removed will still be automatically cleaned up by the PHP interpreter each time the script terminates.

If you need non-blocking semaphores, here is an example how you may implement it. Use a shared memory variable to mark whether or not a lock exists and then use a semaphore around operations against that variable. I'll call my shared variable as 'token'.