Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@naveed125
Created March 12, 2020 05:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save naveed125/9d555fa3d886bbace3dedaf0749b4fbe to your computer and use it in GitHub Desktop.
Save naveed125/9d555fa3d886bbace3dedaf0749b4fbe to your computer and use it in GitHub Desktop.
Sample code showing usage of SET with NX to acquire a semaphore lock
<?php
// uses Predis
// see https://github.com/nrk/predis
use Predis\Client as PredisClient;
$client = new PredisClient();
// connect to the local redis server
$client->connect();
// synchronized code block
$key = 'lock';
if(getLock($client, $key)) {
echo "Lock acquired\n";
// do something useful here
sleep(1);
// release the lock
$client->del([$key]);
}
else {
echo ("Failed to acquire lock\n");
}
/**
* Acquire a lock, notice use of NX parameter
* @param PredisClient $client
* @param string $key
* @return bool
*/
function getLock(PredisClient $client, $key)
{
// attempts to acquire a lock and
for ($i = 0; $i < 3; $i++) {
$lock = $client->set($key, time(), 'EX', 3, 'NX');
if ($lock) {
return true;
}
// use exponential back-off when retrying
usleep(100 * ($i + 1));
}
return false;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment