Skip to content

Commit f60ce89

Browse files
authored
Merge pull request #26 from utopia-php/update-swoole-lock
refactor: replace Lock with Channel for coroutine safety in Swoole ad…
2 parents 74ba7dc + 2df189c commit f60ce89

File tree

1 file changed

+10
-6
lines changed

1 file changed

+10
-6
lines changed

src/Pools/Adapter/Swoole.php

Lines changed: 10 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -4,19 +4,22 @@
44

55
use Utopia\Pools\Adapter;
66
use Swoole\Coroutine\Channel;
7-
use Swoole\Lock;
87

98
class Swoole extends Adapter
109
{
1110
protected Channel $pool;
1211

13-
/** @var Lock $lock */
14-
protected Lock $lock;
12+
protected Channel $lock;
1513
public function initialize(int $size): static
1614
{
1715
$this->pool = new Channel($size);
1816

19-
$this->lock = new Lock(SWOOLE_MUTEX);
17+
// With channels, the current coroutine suspends and yields control to the event loop,
18+
// allowing other coroutines to continue executing.
19+
// Using a blocking lock freezes the worker thread, causing all coroutines in that
20+
// worker to stop making progress.
21+
$this->lock = new Channel(1);
22+
$this->lock->push(true);
2023

2124
return $this;
2225
}
@@ -60,7 +63,7 @@ public function count(): int
6063
*/
6164
public function synchronized(callable $callback, int $timeout): mixed
6265
{
63-
$acquired = $this->lock->lockwait($timeout);
66+
$acquired = $this->lock->pop($timeout);
6467

6568
if (!$acquired) {
6669
throw new \RuntimeException("Failed to acquire lock within {$timeout} seconds");
@@ -69,7 +72,8 @@ public function synchronized(callable $callback, int $timeout): mixed
6972
try {
7073
return $callback();
7174
} finally {
72-
$this->lock->unlock();
75+
// Guaranteed to have space here; avoid timeouts so the token isn't lost.
76+
$this->lock->push(true);
7377
}
7478
}
7579
}

0 commit comments

Comments
 (0)