]> git.mxchange.org Git - friendica.git/blob - src/Core/Lock/SemaphoreLockDriver.php
redesign of locking & caching
[friendica.git] / src / Core / Lock / SemaphoreLockDriver.php
1 <?php
2
3 namespace Friendica\Core\Lock;
4
5 class SemaphoreLockDriver extends AbstractLockDriver
6 {
7         public function __construct()
8         {
9                 if (!function_exists('sem_get')) {
10                         throw new \Exception('Semaphore lock not supported');
11                 }
12         }
13
14         /**
15          * @brief Creates a semaphore key
16          *
17          * @param string $key Name of the lock
18          *
19          * @return integer the semaphore key
20          */
21         private static function semaphoreKey(string $key): int
22         {
23                 $temp = get_temppath();
24
25                 $file = $temp.'/'.$key.'.sem';
26
27                 if (!file_exists($file)) {
28                         file_put_contents($file, $key);
29                 }
30
31                 return ftok($file, 'f');
32         }
33
34         /**
35          *
36          * @brief Sets a lock for a given name
37          *
38          * @param string $key The Name of the lock
39          * @param integer $timeout Seconds until we give up
40          *
41          * @return boolean Was the lock successful?
42          */
43         public function acquireLock(string $key, int $timeout = 120)
44         {
45                 $this->acquiredLocks[$key] = sem_get(self::semaphoreKey($key));
46                 if ($this->acquiredLocks[$key]) {
47                         return sem_acquire($this->acquiredLocks[$key], ($timeout == 0));
48                 }
49         }
50
51         /**
52          * @brief Removes a lock if it was set by us
53          *
54          * @param string $key Name of the lock
55          *
56          * @return mixed
57          */
58         public function releaseLock(string $key)
59         {
60                 if (empty($this->acquiredLocks[$key])) {
61                         return false;
62                 } else {
63                         $success = @sem_release($this->acquiredLocks[$key]);
64                         unset($this->acquiredLocks[$key]);
65                         return $success;
66                 }
67         }
68 }