Skip to content

Commit a9cb075

Browse files
committed
Merge branch 'master' of github.com:code-orange/redis-counting-semaphore
2 parents bae721c + 88125ea commit a9cb075

File tree

2 files changed

+18
-11
lines changed

2 files changed

+18
-11
lines changed

composer.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,6 @@
2222
"symfony/process": "^4.0"
2323
},
2424
"scripts": {
25-
"test": "php test/index.php"
25+
"test": "@php test/index.php"
2626
}
2727
}

src/Semaphore.php

Lines changed: 17 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -49,16 +49,23 @@ public function acquire($sleep = null, $retries = null) {
4949
// We already have it
5050
return true;
5151
}
52-
$acquired = $this->acquire_fair_with_lock();
53-
if ($acquired) {
54-
return true;
55-
} else {
56-
if ($retries > 0 && $sleep > 0) {
57-
sleep($sleep);
58-
return $this->acquire($sleep, $retries - 1);
52+
53+
if ($sleep == null || $retries == null) {
54+
$acquired = $this->acquire_fair_with_lock();
55+
return $acquired;
56+
}
57+
58+
while ($sleep > 0 && $retries > 0) {
59+
$acquired = $this->acquire_fair_with_lock();
60+
61+
if ($acquired) {
62+
return true;
5963
}
60-
return false;
64+
65+
$retries -= 1;
66+
sleep($sleep);
6167
}
68+
return false;
6269
}
6370

6471
/**
@@ -187,7 +194,7 @@ private function acquire_fair_with_lock() {
187194
}
188195

189196
// From section 6.2 of the book
190-
public function acquire_lock($acquire_timeout = 10) {
197+
private function acquire_lock($acquire_timeout = 10) {
191198
$identifier = (string)Uuid::uuid4();
192199

193200
$end = time() + $acquire_timeout;
@@ -200,7 +207,7 @@ public function acquire_lock($acquire_timeout = 10) {
200207
}
201208
return false;
202209
}
203-
public function release_lock($id) {
210+
private function release_lock($id) {
204211
$lockname = 'lock:' . $this->name;
205212

206213
$res = $this->client->transaction(['watch' => $lockname, 'cas' => true, 'retry' => 1000], function (MultiExec $t) use ($id, $lockname) {

0 commit comments

Comments
 (0)