SymfonyWorld Online 2020
100% online
30+ talks + workshops
Live + Replay watch talks later

The Semaphore Component

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.

Installation

1
$ composer require symfony/semaphore

Note

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.

Usage

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();
$redis->connect('172.17.0.2');

$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.

    $semaphore->release();
}

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.

Note

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.

Tip

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 createLock() method to false.

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