namespace Friendica\Core\Lock;
+use Friendica\Core\Cache;
+
class SemaphoreLockDriver extends AbstractLockDriver
{
+ private static $semaphore = [];
+
public function __construct()
{
if (!function_exists('sem_get')) {
}
/**
- * @brief Creates a semaphore key
- *
- * @param string $key Name of the lock
- *
- * @return integer the semaphore key
+ * (@inheritdoc)
*/
- private static function semaphoreKey(string $key)
+ private static function semaphoreKey($key)
{
$temp = get_temppath();
- $file = $temp.'/'.$key.'.sem';
+ $file = $temp . '/' . $key . '.sem';
if (!file_exists($file)) {
file_put_contents($file, $key);
}
/**
- *
- * @brief Sets a lock for a given name
- *
- * @param string $key The Name of the lock
- * @param integer $timeout Seconds until we give up
- *
- * @return boolean Was the lock successful?
+ * (@inheritdoc)
*/
- public function acquireLock(string $key, int $timeout = 120)
+ public function acquireLock($key, $timeout = 120, $ttl = Cache::FIVE_MINUTES)
{
- $this->acquiredLocks[$key] = sem_get(self::semaphoreKey($key));
- if ($this->acquiredLocks[$key]) {
- return sem_acquire($this->acquiredLocks[$key], ($timeout == 0));
+ 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;
+ }
}
+
+ return false;
}
/**
- * @brief Removes a lock if it was set by us
- *
- * @param string $key Name of the lock
- *
- * @return mixed
+ * (@inheritdoc)
*/
- public function releaseLock(string $key)
+ public function releaseLock($key, $override = false)
{
- if (empty($this->acquiredLocks[$key])) {
+ if (empty(self::$semaphore[$key])) {
return false;
} else {
- $success = @sem_release($this->acquiredLocks[$key]);
- unset($this->acquiredLocks[$key]);
+ $success = @sem_release(self::$semaphore[$key]);
+ unset(self::$semaphore[$key]);
+ $this->markRelease($key);
return $success;
}
}
+
+ /**
+ * (@inheritdoc)
+ */
+ public function isLocked($key)
+ {
+ return isset(self::$semaphore[$key]);
+ }
}