Skip to content

Commit 8912854

Browse files
committed
[Semaphore] Added the component
Few years ago, we have introduced the Lock component. This is a very nice component, but sometime it is not enough. Sometime you need semaphore. This is why I'm introducing this new component. From wikipedia: > 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. A semaphore is simply a variable. This variable is used to solve critical section problems and to achieve process synchronization in the multi processing environment. A trivial semaphore is a plain variable that is changed (for example, incremented or decremented, or toggled) depending on programmer-defined conditions. This new component is more than a variable. This is an abstraction on top of different storage. To make a quick comparison with a lock: * A lock allows only 1 process to access a resource; * A semaphore allow N process to access a resource. Basically, a lock is a semaphore where `N = 1`. PHP exposes some `sem_*` functions like [`sem_acquire`](http://php.net/sem_acquire). This module provides wrappers for the System V IPC family of functions. It includes semaphores, shared memory and inter-process messaging (IPC). The Lock component has a storage that works with theses functions. It uses it with `N = 1`. Wikipedia has some [examples](https://en.wikipedia.org/wiki/Semaphore_(programming)#Examples) But I can add one more commun use case. If you are building an async system that process user data, you may want to priorise all jobs. You can achieve that by running at maximum N jobs per user at the same time. If the user has more resources, you give him more concurrent jobs (so a bigger `N`). Thanks to semaphores, it's pretty easy to know if a new job can be run. I'm not saying the following services are using semaphore, but they may solve the previous problematic with semaphores. Here is some examples: * services like testing platform where a user can test N projects concurrently (travis, circle, appveyor, insight, ...) * services that ingest lots of data (newrelic, datadog, blackfire, segment.io, ...)) * services that send email in batch (campaign monitor, mailchimp, ...) * etc... To do so, since PHP is mono-threaded, you run M PHP workers. And in each worker, you look for for the next job. When you grab a job, you try to acquires a semaphore. If you got it, you process the job. If not you try another job. FTR in other language, like Go, there are no need to run M workers, one is enough. ```php <?php use Symfony\Component\Lock\LockFactory; use Symfony\Component\Lock\Store\RedisStore as LockRedisStore; use Symfony\Component\Semaphore\SemaphoreFactory; use Symfony\Component\Semaphore\Store\RedisStore; require __DIR__.'/vendor/autoload.php'; $redis = new Redis(); $redis->connect('172.17.0.2'); // Internally, Semaphore needs a lock $lock = (new LockFactory(new LockRedisStore($redis)))->createLock('test:lock', 1); // Create a semaphore: // * name = test // * limit = 3 (it means only 3 process are allowed) // * ttl = 10 seconds : Maximum expected semaphore duration in seconds $semaphore = (new SemaphoreFactory($lock, new RedisStore($redis)))->createSemaphore('test', 3, 10); if (!$semaphore->acquire()) { echo "Could not acquire the semaphore\n"; exit(1); } // The semaphore has been acquired // Do the heavy job for ($i = 0; $i < 100; ++$i) { sleep(1); // Before the expiration, refresh the semaphore if the job is not finished yet if ($i % 9 === 0) { $semaphore->refresh(); } } // Release it when finished $semaphore->release(); ``` I looked at [packagist](https://packagist.org/?query=semaphore) and: * most of packages are using a semaphore storage for creating a lock. So there are not relevant here; * some packages need an async framework to be used (amphp for example); * the only packages really implementing a semaphore, has a really low code quality and some bugs. 1. I initially copied the Lock component since the external API is quite similar; 1. I simplified it a lot for the current use case; 1. I implemented the RedisStorage according the [redis book](https://redislabs.com/ebook/part-2-core-concepts/chapter-6-application-components-in-redis/6-3-counting-semaphores/;) 1. I forced a TTL on the storage.
1 parent 6d521d4 commit 8912854

33 files changed

+1707
-1
lines changed

composer.json

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -79,11 +79,12 @@
7979
"symfony/property-info": "self.version",
8080
"symfony/proxy-manager-bridge": "self.version",
8181
"symfony/routing": "self.version",
82+
"symfony/security-bundle": "self.version",
8283
"symfony/security-core": "self.version",
8384
"symfony/security-csrf": "self.version",
8485
"symfony/security-guard": "self.version",
8586
"symfony/security-http": "self.version",
86-
"symfony/security-bundle": "self.version",
87+
"symfony/semaphore": "self.version",
8788
"symfony/sendgrid-mailer": "self.version",
8889
"symfony/serializer": "self.version",
8990
"symfony/stopwatch": "self.version",
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
/.gitignore export-ignore
2+
/phpunit.xml.dist export-ignore
3+
/Tests export-ignore
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
composer.lock
2+
phpunit.xml
3+
vendor/
Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
CHANGELOG
2+
=========
3+
4+
5.2.0
5+
-----
6+
7+
* Introduced the component as experimental
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
<?php
2+
3+
/*
4+
* This file is part of the Symfony package.
5+
*
6+
* (c) Fabien Potencier <fabien@symfony.com>
7+
*
8+
* For the full copyright and license information, please view the LICENSE
9+
* file that was distributed with this source code.
10+
*/
11+
12+
namespace Symfony\Component\Semaphore\Exception;
13+
14+
/**
15+
* Base ExceptionInterface for the Semaphore Component.
16+
*
17+
* @experimental in 5.2
18+
*
19+
* @author Jérémy Derussé <jeremy@derusse.com>
20+
*/
21+
interface ExceptionInterface extends \Throwable
22+
{
23+
}
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
<?php
2+
3+
/*
4+
* This file is part of the Symfony package.
5+
*
6+
* (c) Fabien Potencier <fabien@symfony.com>
7+
*
8+
* For the full copyright and license information, please view the LICENSE
9+
* file that was distributed with this source code.
10+
*/
11+
12+
namespace Symfony\Component\Semaphore\Exception;
13+
14+
/**
15+
* @experimental in 5.2
16+
*
17+
* @author Jérémy Derussé <jeremy@derusse.com>
18+
*/
19+
class InvalidArgumentException extends \InvalidArgumentException implements ExceptionInterface
20+
{
21+
}
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
<?php
2+
3+
/*
4+
* This file is part of the Symfony package.
5+
*
6+
* (c) Fabien Potencier <fabien@symfony.com>
7+
*
8+
* For the full copyright and license information, please view the LICENSE
9+
* file that was distributed with this source code.
10+
*/
11+
12+
namespace Symfony\Component\Semaphore\Exception;
13+
14+
/**
15+
* @experimental in 5.2
16+
*
17+
* @author Grégoire Pineau <lyrixx@lyrixx.info>
18+
*/
19+
class RuntimeException extends \RuntimeException implements ExceptionInterface
20+
{
21+
}
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
<?php
2+
3+
/*
4+
* This file is part of the Symfony package.
5+
*
6+
* (c) Fabien Potencier <fabien@symfony.com>
7+
*
8+
* For the full copyright and license information, please view the LICENSE
9+
* file that was distributed with this source code.
10+
*/
11+
12+
namespace Symfony\Component\Semaphore\Exception;
13+
14+
use Symfony\Component\Semaphore\Key;
15+
16+
/**
17+
* SemaphoreAcquiringException is thrown when an issue happens during the acquisition of a semaphore.
18+
*
19+
* @experimental in 5.2
20+
*
21+
* @author Jérémy Derussé <jeremy@derusse.com>
22+
* @author Grégoire Pineau <lyrixx@lyrixx.info>
23+
*/
24+
class SemaphoreAcquiringException extends \RuntimeException implements ExceptionInterface
25+
{
26+
public function __construct(Key $key, string $message)
27+
{
28+
parent::__construct(sprintf('The semaphore "%s" could not be acquired: %s.', $key, $message));
29+
}
30+
}
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
<?php
2+
3+
/*
4+
* This file is part of the Symfony package.
5+
*
6+
* (c) Fabien Potencier <fabien@symfony.com>
7+
*
8+
* For the full copyright and license information, please view the LICENSE
9+
* file that was distributed with this source code.
10+
*/
11+
12+
namespace Symfony\Component\Semaphore\Exception;
13+
14+
use Symfony\Component\Semaphore\Key;
15+
16+
/**
17+
* SemaphoreExpiredException is thrown when a semaphore may conflict due to a TTL expiration.
18+
*
19+
* @experimental in 5.2
20+
*
21+
* @author Jérémy Derussé <jeremy@derusse.com>
22+
* @author Grégoire Pineau <lyrixx@lyrixx.info>
23+
*/
24+
class SemaphoreExpiredException extends \RuntimeException implements ExceptionInterface
25+
{
26+
public function __construct(Key $key, string $message)
27+
{
28+
parent::__construct(sprintf('The semaphore "%s" has expired: %s.', $key, $message));
29+
}
30+
}
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
<?php
2+
3+
/*
4+
* This file is part of the Symfony package.
5+
*
6+
* (c) Fabien Potencier <fabien@symfony.com>
7+
*
8+
* For the full copyright and license information, please view the LICENSE
9+
* file that was distributed with this source code.
10+
*/
11+
12+
namespace Symfony\Component\Semaphore\Exception;
13+
14+
use Symfony\Component\Semaphore\Key;
15+
16+
/**
17+
* SemaphoreReleasingException is thrown when an issue happens during the release of a semaphore.
18+
*
19+
* @experimental in 5.2
20+
*
21+
* @author Jérémy Derussé <jeremy@derusse.com>
22+
* @author Grégoire Pineau <lyrixx@lyrixx.info>
23+
*/
24+
class SemaphoreReleasingException extends \RuntimeException implements ExceptionInterface
25+
{
26+
public function __construct(Key $key, string $message)
27+
{
28+
parent::__construct(sprintf('The semaphore "%s" could not be released: %s.', $key, $message));
29+
}
30+
}

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy