1 | <?php |
||
12 | class Semaphore implements LockInterface |
||
13 | { |
||
14 | /** |
||
15 | * create a lock instance |
||
16 | * |
||
17 | * @param $key |
||
18 | * @return Semaphore |
||
19 | */ |
||
20 | 10 | public static function create($key) |
|
24 | |||
25 | /** |
||
26 | * @var |
||
27 | */ |
||
28 | private $lock_id; |
||
29 | |||
30 | /** |
||
31 | * @var bool |
||
32 | */ |
||
33 | private $locked = false; |
||
34 | |||
35 | /** |
||
36 | * init a lock |
||
37 | * |
||
38 | * @param $key |
||
39 | * @throws \RuntimeException |
||
40 | */ |
||
41 | 10 | private function __construct($key) |
|
47 | |||
48 | /** |
||
49 | * release lock |
||
50 | * |
||
51 | * @throws \RuntimeException |
||
52 | */ |
||
53 | 10 | public function __destruct() |
|
59 | |||
60 | |||
61 | /** |
||
62 | * get a lock |
||
63 | * |
||
64 | * @param bool $blocking |
||
65 | * @return bool |
||
66 | */ |
||
67 | 7 | public function acquire($blocking = true) |
|
68 | { |
||
69 | 7 | if ($this->locked) { |
|
70 | 3 | throw new \RuntimeException("already lock by yourself"); |
|
71 | } |
||
72 | |||
73 | 7 | if ($blocking === false) { |
|
74 | 1 | if (version_compare(PHP_VERSION, '5.6.0') < 0) { |
|
75 | throw new \RuntimeException("php version is at least 5.6.0 for param blocking"); |
||
76 | } |
||
77 | 1 | if (!sem_acquire($this->lock_id, true)) { |
|
78 | 1 | return false; |
|
79 | } |
||
80 | 1 | $this->locked = true; |
|
81 | |||
82 | 1 | return true; |
|
83 | } |
||
84 | |||
85 | 6 | if (!sem_acquire($this->lock_id)) { |
|
86 | return false; |
||
87 | } |
||
88 | 6 | $this->locked = true; |
|
89 | |||
90 | 6 | return true; |
|
91 | } |
||
92 | |||
93 | /** |
||
94 | * release lock |
||
95 | * |
||
96 | * @return bool |
||
97 | * @throws \RuntimeException |
||
98 | */ |
||
99 | 10 | public function release() |
|
112 | |||
113 | /** |
||
114 | * is locked |
||
115 | * |
||
116 | * @return bool |
||
117 | */ |
||
118 | 10 | public function isLocked() |
|
122 | |||
123 | /** |
||
124 | * Semaphore requires a numeric value as the key |
||
125 | * |
||
126 | * @param $identifier |
||
127 | * @return int |
||
128 | */ |
||
129 | 10 | protected function _stringToSemKey($identifier) |
|
138 | } |