123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115 |
- <?php
- namespace yii\mutex;
- use yii\base\Component;
- abstract class Mutex extends Component
- {
-
- public $autoRelease = true;
-
- private $_locks = [];
-
- public function init()
- {
- if ($this->autoRelease) {
- $locks = &$this->_locks;
- register_shutdown_function(function () use (&$locks) {
- foreach ($locks as $lock) {
- $this->release($lock);
- }
- });
- }
- }
-
- public function acquire($name, $timeout = 0)
- {
- if (!in_array($name, $this->_locks, true) && $this->acquireLock($name, $timeout)) {
- $this->_locks[] = $name;
- return true;
- }
- return false;
- }
-
- public function release($name)
- {
- if ($this->releaseLock($name)) {
- $index = array_search($name, $this->_locks);
- if ($index !== false) {
- unset($this->_locks[$index]);
- }
- return true;
- }
- return false;
- }
-
- abstract protected function acquireLock($name, $timeout = 0);
-
- abstract protected function releaseLock($name);
- }
|