-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathSwoole.php
More file actions
75 lines (63 loc) · 1.93 KB
/
Swoole.php
File metadata and controls
75 lines (63 loc) · 1.93 KB
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
<?php
namespace Utopia\Pools\Adapter;
use Utopia\Pools\Adapter;
use Swoole\Coroutine\Channel;
use Swoole\Lock;
class Swoole extends Adapter
{
protected Channel $pool;
/** @var Lock $lock */
protected Lock $lock;
public function initialize(int $size): static
{
$this->pool = new Channel($size);
$this->lock = new Lock(SWOOLE_MUTEX);
return $this;
}
public function push(mixed $connection): static
{
// Push connection to channel
$this->pool->push($connection);
return $this;
}
/**
* Pop an item from the pool.
*
* @param int $timeout Timeout in seconds. Use 0 for non-blocking pop.
* @return mixed|false Returns the pooled value, or false if the pool is empty
* or the timeout expires.
*/
public function pop(int $timeout): mixed
{
return $this->pool->pop($timeout);
}
public function count(): int
{
$length = $this->pool->length();
return is_int($length) ? $length : 0;
}
/**
* Executes a callback while holding a lock.
*
* The lock is acquired before invoking the callback and is always released
* afterward, even if the callback throws an exception.
*
* @param callable $callback Callback to execute within the critical section.
* @param int $timeout Maximum time (in seconds) to wait for the lock.
* @return mixed The value returned by the callback.
*
* @throws \RuntimeException If the lock cannot be acquired within the timeout.
*/
public function synchronized(callable $callback, int $timeout): mixed
{
$acquired = $this->lock->lockwait($timeout);
if (!$acquired) {
throw new \RuntimeException("Failed to acquire lock within {$timeout} seconds");
}
try {
return $callback();
} finally {
$this->lock->unlock();
}
}
}