3 * @copyright Copyright (C) 2010-2021, the Friendica project
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\Type;
24 use Friendica\Core\Cache\Enum\Duration;
25 use Friendica\Core\Lock\Enum\Type;
26 use function get_temppath;
28 class SemaphoreLock extends BaseLock
30 private static $semaphore = [];
32 public function __construct()
34 if (!function_exists('sem_get')) {
35 throw new \Exception('Semaphore lock not supported');
42 private static function semaphoreKey($key)
46 $temp = get_temppath();
48 $file = $temp . '/' . $key . '.sem';
50 if (!file_exists($file)) {
51 $success = !empty(file_put_contents($file, $key));
54 return $success ? ftok($file, 'f') : false;
60 public function acquire($key, $timeout = 120, $ttl = Duration::FIVE_MINUTES)
62 self::$semaphore[$key] = sem_get(self::semaphoreKey($key));
63 if (!empty(self::$semaphore[$key])) {
64 if ((bool)sem_acquire(self::$semaphore[$key], ($timeout === 0))) {
65 $this->markAcquire($key);
76 * @param bool $override not necessary parameter for semaphore locks since the lock lives as long as the execution
77 * of the using function
79 public function release($key, $override = false)
83 if (!empty(self::$semaphore[$key])) {
85 $success = @sem_release(self::$semaphore[$key]);
86 unset(self::$semaphore[$key]);
87 $this->markRelease($key);
88 } catch (\Exception $exception) {
99 public function isLocked($key)
101 return isset(self::$semaphore[$key]);
107 public function getName()
109 return Type::SEMAPHORE;
115 public function getLocks(string $prefix = '')
117 // We can just return our own semaphore keys, since we don't know
118 // the state of other semaphores, even if the .sem files exists
119 $keys = array_keys(self::$semaphore);
121 if (empty($prefix)) {
126 foreach ($keys as $key) {
127 if (strpos($key, $prefix) === 0) {
128 array_push($result, $key);
139 public function releaseAll($override = false)
141 // Semaphores are just alive during a run, so there is no need to release
142 // You can just release your own locks
143 return parent::releaseAll($override);