3 * @copyright Copyright (C) 2020, Friendica
5 * @license GNU AGPL version 3 or any later version
7 * This program is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU Affero General Public License as
9 * published by the Free Software Foundation, either version 3 of the
10 * License, or (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU Affero General Public License for more details.
17 * You should have received a copy of the GNU Affero General Public License
18 * along with this program. If not, see <https://www.gnu.org/licenses/>.
22 namespace Friendica\Core\Lock;
24 use Friendica\Core\BaseLock;
25 use Friendica\Core\Cache\Duration;
27 class SemaphoreLock extends BaseLock
29 private static $semaphore = [];
31 public function __construct()
33 if (!function_exists('sem_get')) {
34 throw new \Exception('Semaphore lock not supported');
41 private static function semaphoreKey($key)
45 $temp = get_temppath();
47 $file = $temp . '/' . $key . '.sem';
49 if (!file_exists($file)) {
50 $success = !empty(file_put_contents($file, $key));
53 return $success ? ftok($file, 'f') : false;
59 public function acquire($key, $timeout = 120, $ttl = Duration::FIVE_MINUTES)
61 self::$semaphore[$key] = sem_get(self::semaphoreKey($key));
62 if (!empty(self::$semaphore[$key])) {
63 if ((bool)sem_acquire(self::$semaphore[$key], ($timeout === 0))) {
64 $this->markAcquire($key);
75 * @param bool $override not necessary parameter for semaphore locks since the lock lives as long as the execution
76 * of the using function
78 public function release($key, $override = false)
82 if (!empty(self::$semaphore[$key])) {
84 $success = @sem_release(self::$semaphore[$key]);
85 unset(self::$semaphore[$key]);
86 $this->markRelease($key);
87 } catch (\Exception $exception) {
98 public function isLocked($key)
100 return isset(self::$semaphore[$key]);
106 public function getName()
108 return Type::SEMAPHORE;
114 public function getLocks(string $prefix = '')
116 // We can just return our own semaphore keys, since we don't know
117 // the state of other semaphores, even if the .sem files exists
118 $keys = array_keys(self::$semaphore);
120 if (empty($prefix)) {
125 foreach ($keys as $key) {
126 if (strpos($key, $prefix) === 0) {
127 array_push($result, $key);
138 public function releaseAll($override = false)
140 // Semaphores are just alive during a run, so there is no need to release
141 // You can just release your own locks
142 return parent::releaseAll($override);