Skip to content

The Semaphore Component

Edit this page

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

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 SemaphoreFactory class, which in turn requires another class to manage the storage:

1
2
3
4
5
6
7
8
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 processes allowed. Then, a call to the acquire() method will try to acquire the semaphore:

1
2
3
4
5
6
7
8
9
// ...
$semaphore = $factory->createSemaphore('pdf-invoice-generation', 2);

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

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

Using Locks as Semaphore Stores

You can also use the LockStore to use any Lock component backend (flock, Redis, PDO, etc.) as a semaphore store:

1
2
3
4
5
6
7
8
use Symfony\Component\Lock\LockFactory;
use Symfony\Component\Lock\Store\FlockStore;
use Symfony\Component\Semaphore\SemaphoreFactory;
use Symfony\Component\Semaphore\Store\LockStore;

$lockFactory = new LockFactory(new FlockStore());
$store = new LockStore($lockFactory);
$factory = new SemaphoreFactory($store);

When using the FrameworkBundle, you can configure this with the lock:// DSN:

1
2
3
4
# config/packages/semaphore.yaml
framework:
    lock: 'flock'
    semaphore: 'lock://'

You can also reference a specific named lock resource using lock://name:

1
2
3
4
5
6
7
8
# config/packages/semaphore.yaml
framework:
    lock:
        default: 'flock'
        my_locks: '%env(REDIS_DSN)%'
    semaphore:
        default: 'lock://'          # uses lock.default.factory
        other: 'lock://my_locks'    # uses lock.my_locks.factory

8.1

The LockStore was introduced in Symfony 8.1.

Serializing Semaphores

8.1

Support for serializing semaphores was introduced in Symfony 8.1.

The Key contains the state of the Semaphore and can be serialized. This allows acquiring a semaphore in one process and releasing it in another, which is useful for workflows, message queues, or any scenario where the acquire and release happen in different contexts.

First, create the semaphore and acquire a slot:

1
2
3
4
5
6
7
8
9
10
11
12
13
use Symfony\Component\Semaphore\Key;

$key = new Key('pdf-generation', 5);  // 5 concurrent slots available
$semaphore = $factory->createSemaphoreFromKey(
    $key,
    300,   // ttl
    false  // autoRelease
);

if ($semaphore->acquire()) {
    // dispatch to worker, passing $key
    $this->bus->dispatch(new GeneratePdfMessage($document, $key));
}

Then, in the worker, use the key to reconstruct and release the semaphore:

1
2
3
4
5
6
7
$semaphore = $factory->createSemaphoreFromKey($key, 300, false);

try {
    // do work
} finally {
    $semaphore->release();
}

Note

Don't forget to set the autoRelease argument to false in the Semaphore instantiation to avoid releasing the semaphore when the destructor is called.

Semaphores can be serialized using both the native PHP serialization system and its serialize function, or using the Serializer component.

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