Skip to content

Instantly share code, notes, and snippets.

@qkdreyer
Last active November 30, 2021 08:32
Show Gist options
  • Save qkdreyer/b717158e846479368551a511ace6dd82 to your computer and use it in GitHub Desktop.
Save qkdreyer/b717158e846479368551a511ace6dd82 to your computer and use it in GitHub Desktop.
<?php
function exists($zk, $res, $token) {
try {
return $zk->get($res) == $token;
} catch (\ZookeeperException $ex) {
return false;
}
}
function acquire($zk, $res, $token) {
if (exists($zk, $res, $token))
return true;
try {
$zk->create($res, $token, [
['perms' => \Zookeeper::PERM_ALL, 'scheme' => 'world', 'id' => 'anyone']
], \Zookeeper::EPHEMERAL);
return true;
} catch (\ZookeeperException $ex) {
if (\Zookeeper::NODEEXISTS === $ex->getCode()) {
return false;
}
throw new Exception($ex);
}
}
function release($zk, $res) {
try {
$zk->delete($res);
} catch (\ZookeeperException $ex) {
}
}
$interval = 10;
$res = '/zzz';
$token = time() . rand(0, 1000000);
$zk = new \Zookeeper('zookeeper:2181');
\Zookeeper::setDebugLevel(Zookeeper::LOG_LEVEL_ERROR);
while (true) {
if (acquire($zk, $res, $token)) {
release($zk, $res);
usleep(1000000);
var_dump('work done ' . $token);
}
usleep(rand(0, $interval * 1000000));
}
@qkdreyer
Copy link
Author

qkdreyer commented Nov 29, 2021

for i in {0..500}; do php zkbench.php &; done;

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment