3 namespace Friendica\Core\Lock;
5 use Friendica\Core\Cache\IMemoryCacheDriver;
7 class CacheLockDriver extends AbstractLockDriver
10 * @var \Friendica\Core\Cache\ICacheDriver;
15 * CacheLockDriver constructor.
17 * @param IMemoryCacheDriver $cache The CacheDriver for this type of lock
19 public function __construct(IMemoryCacheDriver $cache)
21 $this->cache = $cache;
27 public function acquireLock($key, $timeout = 120)
32 $cachekey = self::getLockKey($key);
35 $lock = $this->cache->get($cachekey);
36 // When we do want to lock something that was already locked by us.
37 if ((int)$lock == getmypid()) {
41 // When we do want to lock something new
43 // At first initialize it with "0"
44 $this->cache->add($cachekey, 0);
45 // Now the value has to be "0" because otherwise the key was used by another process meanwhile
46 if ($this->cache->compareSet($cachekey, 0, getmypid(), 300)) {
48 $this->markAcquire($key);
52 if (!$got_lock && ($timeout > 0)) {
53 usleep(rand(10000, 200000));
55 } while (!$got_lock && ((time() - $start) < $timeout));
63 public function releaseLock($key)
65 $cachekey = self::getLockKey($key);
67 $this->cache->compareDelete($cachekey, getmypid());
68 $this->markRelease($key);
74 public function isLocked($key)
76 $cachekey = self::getLockKey($key);
77 $lock = $this->cache->get($cachekey);
78 return isset($lock) && ($lock !== false);
82 * @param string $key The original key
83 * @return string The cache key used for the cache
85 private static function getLockKey($key) {
86 return "lock:" . $key;