Created
August 21, 2019 08:44
-
-
Save mmoreram/752380f204638f49f137986dcd867165 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Enqueue | |
* | |
* @param Locker $locker | |
* @param string $resourceID | |
* @param float $timeout | |
* | |
* @return PromiseInterface | |
*/ | |
public function enqueue( | |
Locker $locker, | |
string $resourceID, | |
float $timeout | |
) : PromiseInterface | |
{ | |
return $this | |
->client | |
->eval(' | |
local resource = ARGV[1]; | |
local locker = ARGV[2]; | |
local hash = resource .. ".hash"; | |
local channel = resource .. ".channel"; | |
local len = redis.call("hlen", hash); | |
redis.call(hset, hash, locker, true); | |
if (len == 0) then | |
redis.call("lpush", channel, '.'); | |
end | |
', 1, $resourceID, $locker->ID()) | |
->then(function() use ($resourceID, $timeout) { | |
var_dump('SI'); | |
return $this | |
->client | |
->blpop($resourceID . '.channel', $timeout); | |
}); | |
} | |
/** | |
* Release | |
* | |
* @param Locker $locker | |
* @param string $resourceID | |
* | |
* @return PromiseInterface | |
*/ | |
public function release( | |
Locker $locker, | |
string $resourceID | |
) : PromiseInterface | |
{ | |
$promise = new FulfilledPromise(); | |
if ($locker->owns()) { | |
$promise->then(function() use ($resourceID, $locker) { | |
return $this | |
->client | |
->eval(' | |
local resource = ARGV[1]; | |
local locker = ARGV[2]; | |
local hash = resource .. ".hash"; | |
local channel = resource .. ".channel"; | |
local len = redis.call("hlen", hash); | |
redis.call(hdel, hash, locker); | |
if (len > 0) then | |
redis.call("lpush", channel, "."); | |
end | |
', 1, $resourceID, $locker->ID()); | |
}); | |
} | |
return $promise; | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$promise = $locker | |
->enqueue() | |
->then(function(Locker $locker) use (&$finished, &$current, $loop, $client) { | |
$this->assertEquals($current, 0); | |
$current++; | |
$finished++; | |
return $client | |
->get('http://google.es') | |
->then(function() use (&$current, $locker) { | |
$this->assertEquals($current, 1); | |
$current--; | |
return $locker; | |
}); | |
}) | |
->then(function(Locker $locker) { | |
return $locker->release(); | |
}); | |
$loop->run(); | |
Block\await($promise, $loop); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment