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