Skip to content

Instantly share code, notes, and snippets.

@icaine
Created July 8, 2014 11:50
Show Gist options
  • Save icaine/7d0ce20d679d5efb9a5d to your computer and use it in GitHub Desktop.
Save icaine/7d0ce20d679d5efb9a5d to your computer and use it in GitHub Desktop.
Simple lock managing mechanism
use Nette\Utils\Strings;
class Lock {
/** @var string */
protected $dir;
/** @var array */
protected $lockHandle = array();
/**
* @param string $dir where to store lock files
*/
function __construct($dir) {
$this->dir = $dir;
}
/**
* @param $key
* @param bool $blocking whether lock should wait or just return false when it tries to get exclusive lock
* @throws LockException
* @return bool
*/
public function lock($key, $blocking = true) {
$filename = $this->getLockFilename($key);
$handle = @fopen($filename, 'w+'); // @ - file may not exist
if (!$handle) {
$handle = fopen($filename, 'w+');
if (!$handle) {
throw new LockException('Could not create file: ' . $filename);
}
}
$this->lockHandle[$key] = $handle;
return flock($handle, $blocking ? LOCK_EX : LOCK_EX | LOCK_NB);
}
public function unlock($key) {
if (isset($this->lockHandle[$key])) {
flock($this->lockHandle[$key], LOCK_UN);
fclose($this->lockHandle[$key]);
unset($this->lockHandle[$key]);
}
}
public function getLockFilename($key) {
$key = Strings::webalize($key);
return usedir($this->dir) . "/$key.lock";
}
public function isLocked($key) {
$lock = $this->lock($key, false);
if ($lock) {
$this->unlock($key);
}
return !$lock;
}
}
class LockException extends \Exception {
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment