diff --git a/composer.json b/composer.json index d9da03e..5f7d86c 100644 --- a/composer.json +++ b/composer.json @@ -16,6 +16,7 @@ "phpunit/phpunit": "~4.0" }, "require": { + "ext-pcntl": "*", "texthtml/php-lock": "~2.1", "predis/predis": "~1.0", "psr/log": "~1.0" diff --git a/src/RedisSimpleLock.php b/src/RedisSimpleLock.php index aa018e8..b739dcd 100644 --- a/src/RedisSimpleLock.php +++ b/src/RedisSimpleLock.php @@ -32,6 +32,8 @@ public function __construct($identifier, Client $client, $ttl = 10000, LoggerInt $this->ttl = $ttl; $this->logger = $logger ?: new NullLogger; $this->id = mt_rand(); + register_shutdown_function($closure = $this->releaseClosure()); + pcntl_signal(SIGINT, $closure); } public function acquire() @@ -48,18 +50,32 @@ public function acquire() public function release() { - $script = <<client->eval($script, 1, $this->identifier, $this->id)) { - $this->logger->debug("lock released on {identifier}", ["identifier" => $this->identifier]); - } + $closure = $this->releaseClosure(); + $closure(); } public function __destruct() { $this->release(); } + + private function releaseClosure() + { + $client = $this->client; + $id = $this->id; + $identifier = $this->identifier; + $logger = $this->logger; + + $closure = function () use ($client, $identifier, $id, $logger) { + $script = <<eval($script, 1, $identifier, $id)) { + $logger->debug("lock released on {identifier}", ["identifier" => $identifier]); + } + }; + return $closure->bindTo(null); + } }