3 namespace Friendica\Core\Lock;
5 class SemaphoreLockDriver extends AbstractLockDriver
7 private static $semaphore = [];
9 public function __construct()
11 if (!function_exists('sem_get')) {
12 throw new \Exception('Semaphore lock not supported');
17 * @brief Creates a semaphore key
19 * @param string $key Name of the lock
21 * @return integer the semaphore key
23 private static function semaphoreKey($key)
25 $temp = get_temppath();
27 $file = $temp.'/'.$key.'.sem';
29 if (!file_exists($file)) {
30 file_put_contents($file, $key);
33 return ftok($file, 'f');
38 * @brief Sets a lock for a given name
40 * @param string $key The Name of the lock
41 * @param integer $timeout Seconds until we give up
43 * @return boolean Was the lock successful?
45 public function acquireLock($key, $timeout = 120)
47 self::$semaphore[$key] = sem_get(self::semaphoreKey($key));
48 if (self::$semaphore[$key]) {
49 if (sem_acquire(self::$semaphore[$key], ($timeout == 0))) {
50 $this->markAcquire($key);
59 * @brief Removes a lock if it was set by us
61 * @param string $key Name of the lock
65 public function releaseLock($key)
67 if (empty(self::$semaphore[$key])) {
70 $success = @sem_release(self::$semaphore[$key]);
71 unset(self::$semaphore[$key]);
72 $this->markRelease($key);
78 * @brief Checks, if a key is currently locked to a process
80 * @param string $key The name of the lock
83 public function isLocked($key)
85 return @sem_get(self::$semaphore[$key]) !== false;