3 namespace Friendica\Core\Lock;
5 class SemaphoreLockDriver extends AbstractLockDriver
7 public function __construct()
9 if (!function_exists('sem_get')) {
10 throw new \Exception('Semaphore lock not supported');
15 * @brief Creates a semaphore key
17 * @param string $key Name of the lock
19 * @return integer the semaphore key
21 private static function semaphoreKey(string $key)
23 $temp = get_temppath();
25 $file = $temp.'/'.$key.'.sem';
27 if (!file_exists($file)) {
28 file_put_contents($file, $key);
31 return ftok($file, 'f');
36 * @brief Sets a lock for a given name
38 * @param string $key The Name of the lock
39 * @param integer $timeout Seconds until we give up
41 * @return boolean Was the lock successful?
43 public function acquireLock(string $key, int $timeout = 120)
45 $this->acquiredLocks[$key] = sem_get(self::semaphoreKey($key));
46 if ($this->acquiredLocks[$key]) {
47 return sem_acquire($this->acquiredLocks[$key], ($timeout == 0));
52 * @brief Removes a lock if it was set by us
54 * @param string $key Name of the lock
58 public function releaseLock(string $key)
60 if (empty($this->acquiredLocks[$key])) {
63 $success = @sem_release($this->acquiredLocks[$key]);
64 unset($this->acquiredLocks[$key]);