2018-06-28 16:57:17 -04:00
|
|
|
<?php
|
|
|
|
|
|
|
|
namespace Friendica\Core\Lock;
|
|
|
|
|
2018-07-07 13:46:16 -04:00
|
|
|
use Friendica\Core\Cache;
|
|
|
|
|
2019-08-04 09:51:49 -04:00
|
|
|
class SemaphoreLock extends Lock
|
2018-06-28 16:57:17 -04:00
|
|
|
{
|
2018-07-04 17:37:22 -04:00
|
|
|
private static $semaphore = [];
|
|
|
|
|
2018-06-28 16:57:17 -04:00
|
|
|
public function __construct()
|
|
|
|
{
|
|
|
|
if (!function_exists('sem_get')) {
|
|
|
|
throw new \Exception('Semaphore lock not supported');
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
2018-07-05 01:59:56 -04:00
|
|
|
* (@inheritdoc)
|
2018-06-28 16:57:17 -04:00
|
|
|
*/
|
2018-06-28 17:06:14 -04:00
|
|
|
private static function semaphoreKey($key)
|
2018-06-28 16:57:17 -04:00
|
|
|
{
|
|
|
|
$temp = get_temppath();
|
|
|
|
|
2018-07-05 14:57:31 -04:00
|
|
|
$file = $temp . '/' . $key . '.sem';
|
2018-06-28 16:57:17 -04:00
|
|
|
|
|
|
|
if (!file_exists($file)) {
|
|
|
|
file_put_contents($file, $key);
|
|
|
|
}
|
|
|
|
|
|
|
|
return ftok($file, 'f');
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
2018-07-05 01:59:56 -04:00
|
|
|
* (@inheritdoc)
|
2018-06-28 16:57:17 -04:00
|
|
|
*/
|
2018-07-07 13:46:16 -04:00
|
|
|
public function acquireLock($key, $timeout = 120, $ttl = Cache::FIVE_MINUTES)
|
2018-06-28 16:57:17 -04:00
|
|
|
{
|
2018-07-04 17:37:22 -04:00
|
|
|
self::$semaphore[$key] = sem_get(self::semaphoreKey($key));
|
|
|
|
if (self::$semaphore[$key]) {
|
|
|
|
if (sem_acquire(self::$semaphore[$key], ($timeout == 0))) {
|
|
|
|
$this->markAcquire($key);
|
|
|
|
return true;
|
|
|
|
}
|
2018-06-28 16:57:17 -04:00
|
|
|
}
|
2018-07-04 17:37:22 -04:00
|
|
|
|
|
|
|
return false;
|
2018-06-28 16:57:17 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
2018-07-05 01:59:56 -04:00
|
|
|
* (@inheritdoc)
|
2018-06-28 16:57:17 -04:00
|
|
|
*/
|
2019-02-24 06:24:09 -05:00
|
|
|
public function releaseLock($key, $override = false)
|
2018-06-28 16:57:17 -04:00
|
|
|
{
|
2018-07-04 17:37:22 -04:00
|
|
|
if (empty(self::$semaphore[$key])) {
|
2018-06-28 16:57:17 -04:00
|
|
|
return false;
|
|
|
|
} else {
|
2018-07-04 17:37:22 -04:00
|
|
|
$success = @sem_release(self::$semaphore[$key]);
|
|
|
|
unset(self::$semaphore[$key]);
|
|
|
|
$this->markRelease($key);
|
2018-06-28 16:57:17 -04:00
|
|
|
return $success;
|
|
|
|
}
|
|
|
|
}
|
2018-07-04 17:37:22 -04:00
|
|
|
|
|
|
|
/**
|
2018-07-05 01:59:56 -04:00
|
|
|
* (@inheritdoc)
|
2018-07-04 17:37:22 -04:00
|
|
|
*/
|
|
|
|
public function isLocked($key)
|
|
|
|
{
|
2018-07-05 14:57:31 -04:00
|
|
|
return isset(self::$semaphore[$key]);
|
2018-07-04 17:37:22 -04:00
|
|
|
}
|
2018-06-28 16:57:17 -04:00
|
|
|
}
|