-
-
Notifications
You must be signed in to change notification settings - Fork 31
Expand file tree
/
Copy pathMutex.php
More file actions
102 lines (90 loc) · 1.89 KB
/
Mutex.php
File metadata and controls
102 lines (90 loc) · 1.89 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
<?php
/**
* This file is part of ninja-mutex.
*
* (C) Kamil Dziedzic <arvenil@klecza.pl>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace NinjaMutex;
use NinjaMutex\Lock\LockInterface;
/**
* Mutex
*
* @author Kamil Dziedzic <arvenil@klecza.pl>
*/
class Mutex
{
/**
* Lock implementor
*
* @var LockInterface
*/
protected $lockImplementor;
/**
* Name of lock
*
* @var string
*/
protected $name;
/**
* Lock counter to protect against recursive deadlock
*
* @var integer
*/
protected $counter = 0;
/**
* @param string $name
* @param LockInterface $lockImplementor
*/
public function __construct($name, LockInterface $lockImplementor)
{
$this->name = $name;
$this->lockImplementor = $lockImplementor;
}
/**
* @param int|null $timeout
* @return bool
*/
public function acquireLock($timeout = null)
{
if ($this->counter > 0 ||
$this->lockImplementor->acquireLock($this->name, $timeout)) {
$this->counter++;
return true;
}
return false;
}
/**
* @return bool
*/
public function releaseLock()
{
if ($this->counter > 0) {
$this->counter--;
if ($this->counter > 0 ||
$this->lockImplementor->releaseLock($this->name)) {
return true;
}
$this->counter++;
}
return false;
}
/**
* Check if Mutex is acquired
*
* @return bool
*/
public function isAcquired()
{
return $this->counter > 0;
}
/**
* @return bool
*/
public function isLocked()
{
return $this->lockImplementor->isLocked($this->name);
}
}