forked from amphp/sync
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPosixSemaphore.php
243 lines (208 loc) · 6.79 KB
/
PosixSemaphore.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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
<?php
namespace Amp\Sync;
use Amp\Coroutine;
use Amp\Delayed;
use Amp\Promise;
/**
* A non-blocking, inter-process POSIX semaphore.
*
* Uses a POSIX message queue to store a queue of permits in a lock-free data structure. This semaphore implementation
* is preferred over other implementations when available, as it provides the best performance.
*
* Not compatible with Windows.
*/
class PosixSemaphore implements Semaphore
{
public const LATENCY_TIMEOUT = 10;
/** @var string */
private $id;
/** @var int The semaphore key. */
private $key;
/** @var int PID of the process that created the semaphore. */
private $initializer = 0;
/** @var resource A message queue of available locks. */
private $queue;
/**
* Creates a new semaphore with a given ID and number of locks.
*
* @param string $id The unique name for the new semaphore.
* @param int $maxLocks The maximum number of locks that can be acquired from the semaphore.
* @param int $permissions Permissions to access the semaphore. Use file permission format specified as 0xxx.
*
* @return PosixSemaphore
* @throws SyncException If the semaphore could not be created due to an internal error.
*/
public static function create(string $id, int $maxLocks, int $permissions = 0600): self
{
if ($maxLocks < 1) {
throw new \Error('Number of locks must be greater than 0');
}
$semaphore = new self($id);
$semaphore->init($maxLocks, $permissions);
return $semaphore;
}
/**
* @param string $id The unique name of the semaphore to use.
*
* @return \Amp\Sync\PosixSemaphore
*/
public static function use(string $id): self
{
$semaphore = new self($id);
$semaphore->open();
return $semaphore;
}
/**
* @param string $id
*
* @throws \Error If the sysvmsg extension is not loaded.
*/
private function __construct(string $id)
{
if (!\extension_loaded("sysvmsg")) {
throw new \Error(__CLASS__ . " requires the sysvmsg extension.");
}
$this->id = $id;
$this->key = self::makeKey($this->id);
}
/**
* Private method to prevent cloning.
*/
private function __clone()
{
}
/**
* Prevent serialization.
*/
public function __sleep()
{
throw new \Error('A semaphore cannot be serialized!');
}
public function getId(): string
{
return $this->id;
}
private function open(): void
{
if (!\msg_queue_exists($this->key)) {
throw new SyncException('No semaphore with that ID found');
}
$this->queue = \msg_get_queue($this->key);
if (!$this->queue) {
throw new SyncException('Failed to open the semaphore.');
}
}
/**
* @param int $maxLocks The maximum number of locks that can be acquired from the semaphore.
* @param int $permissions Permissions to access the semaphore.
*
* @throws SyncException If the semaphore could not be created due to an internal error.
*/
private function init(int $maxLocks, int $permissions): void
{
if (\msg_queue_exists($this->key)) {
throw new SyncException('A semaphore with that ID already exists');
}
$this->queue = \msg_get_queue($this->key, $permissions);
if (!$this->queue) {
throw new SyncException('Failed to create the semaphore.');
}
$this->initializer = \getmypid();
// Fill the semaphore with locks.
while (--$maxLocks >= 0) {
$this->release($maxLocks);
}
}
/**
* Gets the access permissions of the semaphore.
*
* @return int A permissions mode.
*/
public function getPermissions(): int
{
$stat = \msg_stat_queue($this->queue);
return $stat['msg_perm.mode'];
}
/**
* Sets the access permissions of the semaphore.
*
* The current user must have access to the semaphore in order to change the permissions.
*
* @param int $mode A permissions mode to set.
*
* @throws SyncException If the operation failed.
*/
public function setPermissions(int $mode)
{
if (!\msg_set_queue($this->queue, ['msg_perm.mode' => $mode])) {
throw new SyncException('Failed to change the semaphore permissions.');
}
}
public function acquire(): Promise
{
return new Coroutine($this->doAcquire());
}
/**
* {@inheritdoc}
*/
private function doAcquire(): \Generator
{
do {
// Attempt to acquire a lock from the semaphore.
if (@\msg_receive($this->queue, 0, $type, 1, $id, false, \MSG_IPC_NOWAIT, $errno)) {
// A free lock was found, so resolve with a lock object that can
// be used to release the lock.
return new Lock(\unpack("C", $id)[1], function (Lock $lock) {
$this->release($lock->getId());
});
}
// Check for unusual errors.
if ($errno !== \MSG_ENOMSG) {
throw new SyncException(\sprintf('Failed to acquire a lock; errno: %d', $errno));
}
} while (yield new Delayed(self::LATENCY_TIMEOUT, true));
}
/**
* Removes the semaphore if it still exists.
*
* @throws SyncException If the operation failed.
*/
public function __destruct()
{
if ($this->initializer === 0 || $this->initializer !== \getmypid()) {
return;
}
if (\PHP_VERSION_ID < 80000 && (!\is_resource($this->queue) || !\msg_queue_exists($this->key))) {
return;
}
if (\PHP_VERSION_ID >= 80000 && (!$this->queue instanceof \SysvMessageQueue || !\msg_queue_exists($this->key))) {
return;
}
\msg_remove_queue($this->queue);
}
/**
* Releases a lock from the semaphore.
*
* @param int $id Lock identifier.
*
* @throws SyncException If the operation failed.
*/
protected function release(int $id)
{
if (!$this->queue) {
return; // Queue already destroyed.
}
// Call send in non-blocking mode. If the call fails because the queue
// is full, then the number of locks configured is too large.
if (!@\msg_send($this->queue, 1, \pack("C", $id), false, false, $errno)) {
if ($errno === \MSG_EAGAIN) {
throw new SyncException('The semaphore size is larger than the system allows.');
}
throw new SyncException('Failed to release the lock.');
}
}
private static function makeKey(string $id): int
{
return \abs(\unpack("l", \md5($id, true))[1]);
}
}