1 | <?php |
||
19 | class Mutex |
||
20 | { |
||
21 | /** |
||
22 | * Lock implementor |
||
23 | * |
||
24 | * @var LockInterface |
||
25 | */ |
||
26 | protected $lockImplementor; |
||
27 | |||
28 | /** |
||
29 | * Name of lock |
||
30 | * |
||
31 | * @var string |
||
32 | */ |
||
33 | protected $name; |
||
34 | |||
35 | /** |
||
36 | * Lock counter to protect against recursive deadlock |
||
37 | * |
||
38 | * @var integer |
||
39 | */ |
||
40 | protected $counter = 0; |
||
41 | |||
42 | /** |
||
43 | * @param string $name |
||
44 | * @param LockInterface $lockImplementor |
||
45 | */ |
||
46 | 155 | public function __construct($name, LockInterface $lockImplementor) |
|
51 | |||
52 | /** |
||
53 | * @param int|null $timeout |
||
54 | * @return bool |
||
55 | */ |
||
56 | 127 | public function acquireLock($timeout = null) |
|
57 | { |
||
58 | 127 | if ($this->counter > 0 || |
|
59 | 127 | $this->lockImplementor->acquireLock($this->name, $timeout)) { |
|
60 | 127 | $this->counter++; |
|
61 | |||
62 | 127 | return true; |
|
63 | } |
||
64 | |||
65 | 28 | return false; |
|
66 | } |
||
67 | |||
68 | /** |
||
69 | * @return bool |
||
70 | */ |
||
71 | 127 | public function releaseLock() |
|
72 | { |
||
73 | 127 | if ($this->counter > 0) { |
|
74 | 127 | $this->counter--; |
|
75 | 127 | if ($this->counter > 0 || |
|
76 | 127 | $this->lockImplementor->releaseLock($this->name)) { |
|
77 | 127 | return true; |
|
78 | } |
||
79 | 1 | $this->counter++; |
|
80 | 1 | } |
|
81 | |||
82 | 15 | return false; |
|
83 | } |
||
84 | |||
85 | /** |
||
86 | * Try to release any obtained locks when object is destroyed |
||
87 | * |
||
88 | * This is a safe guard for cases when your php script dies unexpectedly. |
||
89 | * It's not guaranteed it will work either. |
||
90 | * |
||
91 | * You should not depend on __destruct() to release your locks, |
||
92 | * instead release them with `$released = $this->releaseLock()`A |
||
93 | * and check `$released` if lock was properly released |
||
94 | */ |
||
95 | 155 | public function __destruct() |
|
96 | { |
||
97 | 155 | while ($this->isAcquired()) { |
|
98 | 85 | $released = $this->releaseLock(); |
|
99 | 85 | if (!$released) { |
|
100 | 1 | throw new UnrecoverableMutexException(sprintf( |
|
101 | 1 | 'Cannot release lock in Mutex __destruct(): %s', |
|
102 | 1 | $this->name |
|
103 | 1 | )); |
|
104 | } |
||
105 | 85 | } |
|
106 | 155 | } |
|
107 | |||
108 | /** |
||
109 | * Check if Mutex is acquired |
||
110 | * |
||
111 | * @return bool |
||
112 | */ |
||
113 | 155 | public function isAcquired() |
|
114 | { |
||
115 | 155 | return $this->counter > 0; |
|
116 | } |
||
117 | |||
118 | /** |
||
119 | * @return bool |
||
120 | */ |
||
121 | 84 | public function isLocked() |
|
125 | } |
||
126 |