1 | <?php |
||
32 | abstract class Mutex extends Component |
||
33 | { |
||
34 | /** |
||
35 | * @var bool whether all locks acquired in this process (i.e. local locks) must be released automatically |
||
36 | * before finishing script execution. Defaults to true. Setting this property to true means that all locks |
||
37 | * acquired in this process must be released (regardless of errors or exceptions). |
||
38 | */ |
||
39 | public $autoRelease = true; |
||
40 | |||
41 | /** |
||
42 | * @var string[] names of the locks acquired by the current PHP process. |
||
43 | */ |
||
44 | private $_locks = []; |
||
45 | |||
46 | |||
47 | /** |
||
48 | * Initializes the Mutex component. |
||
49 | */ |
||
50 | 4 | public function init() |
|
51 | { |
||
52 | 4 | if ($this->autoRelease) { |
|
53 | 4 | $locks = &$this->_locks; |
|
54 | 4 | register_shutdown_function(function () use (&$locks) { |
|
55 | foreach ($locks as $lock) { |
||
56 | $this->release($lock); |
||
57 | } |
||
58 | 4 | }); |
|
59 | 4 | } |
|
60 | 4 | } |
|
61 | |||
62 | /** |
||
63 | * Acquires a lock by name. |
||
64 | * @param string $name of the lock to be acquired. Must be unique. |
||
65 | * @param int $timeout time to wait for lock to be released. Defaults to zero meaning that method will return |
||
66 | * false immediately in case lock was already acquired. |
||
67 | * @return bool lock acquiring result. |
||
68 | */ |
||
69 | 7 | public function acquire($name, $timeout = 0) |
|
79 | |||
80 | /** |
||
81 | * Releases acquired lock. This method will return false in case the lock was not found. |
||
82 | * @param string $name of the lock to be released. This lock must already exist. |
||
83 | * @return bool lock release result: false in case named lock was not found.. |
||
84 | */ |
||
85 | 4 | public function release($name) |
|
98 | |||
99 | /** |
||
100 | * This method should be extended by a concrete Mutex implementations. Acquires lock by name. |
||
101 | * @param string $name of the lock to be acquired. |
||
102 | * @param int $timeout time to wait for the lock to be released. |
||
103 | * @return bool acquiring result. |
||
104 | */ |
||
105 | abstract protected function acquireLock($name, $timeout = 0); |
||
106 | |||
107 | /** |
||
108 | * This method should be extended by a concrete Mutex implementations. Releases lock by given name. |
||
109 | * @param string $name of the lock to be released. |
||
110 | * @return bool release result. |
||
111 | */ |
||
112 | abstract protected function releaseLock($name); |
||
113 | } |
||
114 |