3 namespace Friendica\Core\Lock;
5 use Friendica\Core\Cache\ICacheDriver;
7 class CacheLockDriver extends AbstractLockDriver
10 * @var \Friendica\Core\Cache\ICacheDriver;
15 * CacheLockDriver constructor.
17 * @param ICacheDriver $cache The CacheDriver for this type of lock
19 public function __construct(ICacheDriver $cache)
21 $this->cache = $cache;
26 * @brief Sets a lock for a given name
28 * @param string $key The Name of the lock
29 * @param integer $timeout Seconds until we give up
31 * @return boolean Was the lock successful?
33 public function acquireLock($key, $timeout = 120)
38 $cachekey = get_app()->get_hostname() . ";lock:" . $key;
41 $lock = $this->cache->get($cachekey);
43 if (!is_bool($lock)) {
46 // When the process id isn't used anymore, we can safely claim the lock for us.
47 // Or we do want to lock something that was already locked by us.
48 if (!posix_kill($pid, 0) || ($pid == getmypid())) {
53 $this->cache->set($cachekey, getmypid(), 300);
57 if (!$got_lock && ($timeout > 0)) {
58 usleep(rand(10000, 200000));
60 } while (!$got_lock && ((time() - $start) < $timeout));
62 $this->markAcquire($key);
68 * @brief Removes a lock if it was set by us
70 * @param string $key Name of the lock
74 public function releaseLock($key)
76 $cachekey = get_app()->get_hostname() . ";lock:" . $key;
77 $lock = $this->cache->get($cachekey);
79 if (!is_bool($lock)) {
80 if ((int)$lock == getmypid()) {
81 $this->cache->delete($cachekey);
85 $this->markRelease($key);