]> git.mxchange.org Git - friendica.git/blob - src/Core/Lock/SemaphoreLockDriver.php
coding standards
[friendica.git] / src / Core / Lock / SemaphoreLockDriver.php
1 <?php
2
3 namespace Friendica\Core\Lock;
4
5 use Friendica\Core\Cache;
6
7 class SemaphoreLockDriver extends AbstractLockDriver
8 {
9         private static $semaphore = [];
10
11         public function __construct()
12         {
13                 if (!function_exists('sem_get')) {
14                         throw new \Exception('Semaphore lock not supported');
15                 }
16         }
17
18         /**
19          * (@inheritdoc)
20          */
21         private static function semaphoreKey($key)
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          * (@inheritdoc)
36          */
37         public function acquireLock($key, $timeout = 120, $ttl = Cache::FIVE_MINUTES)
38         {
39                 self::$semaphore[$key] = sem_get(self::semaphoreKey($key));
40                 if (self::$semaphore[$key]) {
41                         if (sem_acquire(self::$semaphore[$key], ($timeout == 0))) {
42                                 $this->markAcquire($key);
43                                 return true;
44                         }
45                 }
46
47                 return false;
48         }
49
50         /**
51          * (@inheritdoc)
52          */
53         public function releaseLock($key)
54         {
55                 if (empty(self::$semaphore[$key])) {
56                         return false;
57                 } else {
58                         $success = @sem_release(self::$semaphore[$key]);
59                         unset(self::$semaphore[$key]);
60                         $this->markRelease($key);
61                         return $success;
62                 }
63         }
64
65         /**
66          * (@inheritdoc)
67          */
68         public function isLocked($key)
69         {
70                 return isset(self::$semaphore[$key]);
71         }
72 }