1 | <?php |
||
17 | class Semaphore implements LockInterface |
||
18 | { |
||
19 | /** |
||
20 | * create a lock instance |
||
21 | * |
||
22 | * @param $key |
||
23 | * @return Semaphore |
||
24 | */ |
||
25 | 9 | public static function create($key) |
|
26 | { |
||
27 | 9 | return new Semaphore($key); |
|
28 | } |
||
29 | |||
30 | /** |
||
31 | * @var |
||
32 | */ |
||
33 | private $lock_id; |
||
34 | |||
35 | /** |
||
36 | * @var bool |
||
37 | */ |
||
38 | private $locked = false; |
||
39 | |||
40 | /** |
||
41 | * init a lock |
||
42 | * |
||
43 | * @param $key |
||
44 | * @param $count |
||
45 | * @throws \RuntimeException |
||
46 | */ |
||
47 | 9 | private function __construct($key, $count = 1) |
|
53 | |||
54 | /** |
||
55 | * release lock |
||
56 | * |
||
57 | * @throws \RuntimeException |
||
58 | */ |
||
59 | 9 | public function __destruct() |
|
65 | |||
66 | |||
67 | /** |
||
68 | * get a lock |
||
69 | * |
||
70 | * @param bool $blocking |
||
71 | * @return bool |
||
72 | */ |
||
73 | 6 | public function acquire($blocking = true) |
|
74 | { |
||
75 | 6 | if ($this->locked) { |
|
76 | 3 | throw new \RuntimeException("already lock by yourself"); |
|
77 | } |
||
78 | |||
79 | 6 | if ($blocking === false) { |
|
80 | if (version_compare(PHP_VERSION, '5.6.0') < 0) { |
||
81 | throw new \RuntimeException("php version is at least 5.6.0 for param blocking"); |
||
82 | } |
||
83 | if (!sem_acquire($this->lock_id, true)) { |
||
84 | return false; |
||
85 | } |
||
86 | $this->locked = true; |
||
87 | |||
88 | return true; |
||
89 | } |
||
90 | |||
91 | 6 | if (!sem_acquire($this->lock_id)) { |
|
92 | return false; |
||
93 | } |
||
94 | 6 | $this->locked = true; |
|
95 | |||
96 | 6 | return true; |
|
97 | } |
||
98 | |||
99 | /** |
||
100 | * release lock |
||
101 | * |
||
102 | * @return bool |
||
103 | * @throws \RuntimeException |
||
104 | */ |
||
105 | 9 | public function release() |
|
118 | |||
119 | /** |
||
120 | * is locked |
||
121 | * |
||
122 | * @return bool |
||
123 | */ |
||
124 | 9 | public function isLocked() |
|
128 | |||
129 | /** |
||
130 | * Semaphore requires a numeric value as the key |
||
131 | * |
||
132 | * @param $identifier |
||
133 | * @return int |
||
134 | */ |
||
135 | 9 | protected function _stringToSemKey($identifier) |
|
144 | } |