]> git.mxchange.org Git - friendica.git/blob - src/Core/Lock/SemaphoreLockDriver.php
Fixings
[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          * (@inheritdoc)
18          */
19         private static function semaphoreKey($key)
20         {
21                 $temp = get_temppath();
22
23                 $file = $temp . '/' . $key . '.sem';
24
25                 if (!file_exists($file)) {
26                         file_put_contents($file, $key);
27                 }
28
29                 return ftok($file, 'f');
30         }
31
32         /**
33          *
34          * (@inheritdoc)
35          */
36         public function acquireLock($key, $timeout = 120)
37         {
38                 self::$semaphore[$key] = sem_get(self::semaphoreKey($key));
39                 if (self::$semaphore[$key]) {
40                         if (sem_acquire(self::$semaphore[$key], ($timeout == 0))) {
41                                 $this->markAcquire($key);
42                                 return true;
43                         }
44                 }
45
46                 return false;
47         }
48
49         /**
50          * (@inheritdoc)
51          */
52         public function releaseLock($key)
53         {
54                 if (empty(self::$semaphore[$key])) {
55                         return false;
56                 } else {
57                         $success = @sem_release(self::$semaphore[$key]);
58                         unset(self::$semaphore[$key]);
59                         $this->markRelease($key);
60                         return $success;
61                 }
62         }
63
64         /**
65          * (@inheritdoc)
66          */
67         public function isLocked($key)
68         {
69                 return isset(self::$semaphore[$key]);
70         }
71 }