Skip to content

Commit 195f4c7

Browse files
committed
Merge pull request #2 from mathroc/fix/release
fix lock release on fatal error and SIGTERM
2 parents 8457cc4 + 919698f commit 195f4c7

File tree

2 files changed

+25
-8
lines changed

2 files changed

+25
-8
lines changed

composer.json

+1
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@
1616
"phpunit/phpunit": "~4.0"
1717
},
1818
"require": {
19+
"ext-pcntl": "*",
1920
"texthtml/php-lock": "~2.1",
2021
"predis/predis": "~1.0",
2122
"psr/log": "~1.0"

src/RedisSimpleLock.php

+24-8
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,8 @@ public function __construct($identifier, Client $client, $ttl = 10000, LoggerInt
3232
$this->ttl = $ttl;
3333
$this->logger = $logger ?: new NullLogger;
3434
$this->id = mt_rand();
35+
register_shutdown_function($closure = $this->releaseClosure());
36+
pcntl_signal(SIGINT, $closure);
3537
}
3638

3739
public function acquire()
@@ -48,18 +50,32 @@ public function acquire()
4850

4951
public function release()
5052
{
51-
$script = <<<LUA
52-
if redis.call("get", KEYS[1]) == ARGV[1] then
53-
return redis.call("del", KEYS[1])
54-
end
55-
LUA;
56-
if ($this->client->eval($script, 1, $this->identifier, $this->id)) {
57-
$this->logger->debug("lock released on {identifier}", ["identifier" => $this->identifier]);
58-
}
53+
$closure = $this->releaseClosure();
54+
$closure();
5955
}
6056

6157
public function __destruct()
6258
{
6359
$this->release();
6460
}
61+
62+
private function releaseClosure()
63+
{
64+
$client = $this->client;
65+
$id = $this->id;
66+
$identifier = $this->identifier;
67+
$logger = $this->logger;
68+
69+
$closure = function () use ($client, $identifier, $id, $logger) {
70+
$script = <<<LUA
71+
if redis.call("get", KEYS[1]) == ARGV[1] then
72+
return redis.call("del", KEYS[1])
73+
end
74+
LUA;
75+
if ($client->eval($script, 1, $identifier, $id)) {
76+
$logger->debug("lock released on {identifier}", ["identifier" => $identifier]);
77+
}
78+
};
79+
return $closure->bindTo(null);
80+
}
6581
}

0 commit comments

Comments
 (0)