3 namespace Friendica\Core\Lock;
5 use Friendica\Core\Cache;
6 use Friendica\Core\Cache\IMemoryCache;
8 class CacheLock extends Lock
11 * @var string The static prefix of all locks inside the cache
13 const CACHE_PREFIX = 'lock:';
16 * @var \Friendica\Core\Cache\ICache;
21 * CacheLock constructor.
23 * @param IMemoryCache $cache The CacheDriver for this type of lock
25 public function __construct(IMemoryCache $cache)
27 $this->cache = $cache;
33 public function acquire($key, $timeout = 120, $ttl = Cache\Duration::FIVE_MINUTES)
38 $cachekey = self::getLockKey($key);
41 $lock = $this->cache->get($cachekey);
42 // When we do want to lock something that was already locked by us.
43 if ((int)$lock == getmypid()) {
47 // When we do want to lock something new
49 // At first initialize it with "0"
50 $this->cache->add($cachekey, 0);
51 // Now the value has to be "0" because otherwise the key was used by another process meanwhile
52 if ($this->cache->compareSet($cachekey, 0, getmypid(), $ttl)) {
54 $this->markAcquire($key);
58 if (!$got_lock && ($timeout > 0)) {
59 usleep(rand(10000, 200000));
61 } while (!$got_lock && ((time() - $start) < $timeout));
69 public function release($key, $override = false)
71 $cachekey = self::getLockKey($key);
74 $return = $this->cache->delete($cachekey);
76 $return = $this->cache->compareDelete($cachekey, getmypid());
78 $this->markRelease($key);
86 public function isLocked($key)
88 $cachekey = self::getLockKey($key);
89 $lock = $this->cache->get($cachekey);
90 return isset($lock) && ($lock !== false);
96 public function getName()
98 return $this->cache->getName();
104 public function getLocks(string $prefix = '')
106 $locks = $this->cache->getAllKeys(self::CACHE_PREFIX . $prefix);
108 array_walk($locks, function (&$lock, $key) {
109 $lock = substr($lock, strlen(self::CACHE_PREFIX));
118 public function releaseAll($override = false)
120 $success = parent::releaseAll($override);
122 $locks = $this->getLocks();
124 foreach ($locks as $lock) {
125 if (!$this->release($lock, $override)) {
134 * @param string $key The original key
136 * @return string The cache key used for the cache
138 private static function getLockKey($key)
140 return self::CACHE_PREFIX . $key;