-
-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathSemaphoreStore.php
99 lines (81 loc) · 2.37 KB
/
SemaphoreStore.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\Lock\Store;
use Symfony\Component\Lock\BlockingStoreInterface;
use Symfony\Component\Lock\Exception\InvalidArgumentException;
use Symfony\Component\Lock\Exception\LockConflictedException;
use Symfony\Component\Lock\Key;
/**
* SemaphoreStore is a PersistingStoreInterface implementation using Semaphore as store engine.
*
* @author Jérémy Derussé <jeremy@derusse.com>
*/
class SemaphoreStore implements BlockingStoreInterface
{
/**
* Returns whether or not the store is supported.
*
* @internal
*/
public static function isSupported(): bool
{
return \extension_loaded('sysvsem');
}
public function __construct()
{
if (!static::isSupported()) {
throw new InvalidArgumentException('Semaphore extension (sysvsem) is required.');
}
}
public function save(Key $key): void
{
$this->lock($key, false);
}
public function waitAndSave(Key $key): void
{
$this->lock($key, true);
}
private function lock(Key $key, bool $blocking): void
{
if ($key->hasState(__CLASS__)) {
return;
}
$keyId = unpack('i', hash('xxh128', $key, true))[1];
$resource = @sem_get($keyId);
$acquired = $resource && @sem_acquire($resource, !$blocking);
while ($blocking && !$acquired) {
$resource = @sem_get($keyId);
$acquired = $resource && @sem_acquire($resource);
}
if (!$acquired) {
throw new LockConflictedException();
}
$key->setState(__CLASS__, $resource);
$key->markUnserializable();
}
public function delete(Key $key): void
{
// The lock is maybe not acquired.
if (!$key->hasState(__CLASS__)) {
return;
}
$resource = $key->getState(__CLASS__);
sem_remove($resource);
$key->removeState(__CLASS__);
}
public function putOffExpiration(Key $key, float $ttl): void
{
// do nothing, the semaphore locks forever.
}
public function exists(Key $key): bool
{
return $key->hasState(__CLASS__);
}
}