Skip to content

Commit 7b75574

Browse files
committed
acquire mutexes in random order
1 parent 211715a commit 7b75574

File tree

2 files changed

+18
-2
lines changed

2 files changed

+18
-2
lines changed

src/Mutex/DistributedMutex.php

+17-1
Original file line numberDiff line numberDiff line change
@@ -55,7 +55,7 @@ protected function acquireWithToken(string $key, float $expireTimeout)
5555
$notAcquired = 0;
5656
$errored = 0;
5757
$exception = null;
58-
foreach ($this->mutexes as $index => $mutex) {
58+
foreach ($this->getMutexesInRandomOrder() as $index => $mutex) {
5959
try {
6060
if ($this->acquireMutex($mutex, $key, $acquireTimeout - (microtime(true) - $startTs), $expireTimeout)) {
6161
$acquiredIndexes[] = $index;
@@ -138,6 +138,22 @@ protected function releaseWithToken(string $key, string $token): bool
138138
}
139139
}
140140

141+
/**
142+
* @return array<int, AbstractSpinlockMutex>
143+
*/
144+
private function getMutexesInRandomOrder(): array
145+
{
146+
$indexes = array_keys($this->mutexes);
147+
shuffle($indexes);
148+
149+
$res = [];
150+
foreach ($indexes as $index) {
151+
$res[$index] = $this->mutexes[$index];
152+
}
153+
154+
return $res;
155+
}
156+
141157
/**
142158
* @return bool True if the count is the majority
143159
*/

tests/Mutex/DistributedMutexTest.php

+1-1
Original file line numberDiff line numberDiff line change
@@ -93,7 +93,7 @@ public function testTooFewServerToAcquire(int $count, int $available): void
9393
$mutex = $this->createDistributedMutexMock($count);
9494

9595
$i = 0;
96-
$mutex->expects(self::atMost((int) floor($count / 2) + $count - $available))
96+
$mutex->expects(self::atMost((int) floor($count / 2) + $count - $available))
9797
->method('acquireMutex')
9898
->willReturnCallback(static function () use (&$i, $available) {
9999
if ($i++ < $available) {

0 commit comments

Comments
 (0)