The Semaphore Component

5.4 version
Maintained Unmaintained
Symfony 5.4 is backed by Private Packagist.

The Semaphore Component

The Semaphore Component manages semaphores, a mechanism to provide exclusive access to a shared resource.

New in version 5.2: The Semaphore Component was introduced in Symfony 5.2.


$ composer require symfony/semaphore


If you install this component outside of a Symfony application, you must require the vendor/autoload.php file in your code to enable the class autoloading mechanism provided by Composer. Read this article for more details.


In computer science, a semaphore is a variable or abstract data type used to control access to a common resource by multiple processes in a concurrent system such as a multitasking operating system. The main difference with locks is that semaphores allow more than one process to access a resource, whereas locks only allow one process.

Create semaphores with the Symfony\Component\Semaphore\SemaphoreFactory class, which in turn requires another class to manage the storage:

use Symfony\Component\Semaphore\SemaphoreFactory;
use Symfony\Component\Semaphore\Store\RedisStore;

$redis = new Redis();

$store = new RedisStore($redis);
$factory = new SemaphoreFactory($store);

The semaphore is created by calling the createSemaphore() method. Its first argument is an arbitrary string that represents the locked resource. Its second argument is the maximum number of process allowed. Then, a call to the acquire() method will try to acquire the semaphore:

// ...
$semaphore = $factory->createSemaphore('pdf-invoice-generation', 2);

if ($semaphore->acquire()) {
    // The resource "pdf-invoice-generation" is locked.
    // You can compute and generate invoice safely here.


If the semaphore can not be acquired, the method returns false. The acquire() method can be safely called repeatedly, even if the semaphore is already acquired.


Unlike other implementations, the Semaphore component distinguishes semaphores instances even when they are created for the same resource. If a semaphore has to be used by several services, they should share the same Semaphore instance returned by the SemaphoreFactory::createSemaphore method.


If you don’t release the semaphore explicitly, it will be released automatically on instance destruction. In some cases, it can be useful to lock a resource across several requests. To disable the automatic release behavior, set the fifth argument of the createSemaphore() method to false.

This work, including the code samples, is licensed under a Creative Commons BY-SA 3.0 license.