-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathMutexAdapter.php
More file actions
107 lines (92 loc) · 2.27 KB
/
MutexAdapter.php
File metadata and controls
107 lines (92 loc) · 2.27 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
103
104
105
106
107
<?php
/*
* This file is part of the Mutex Library.
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace AMF\Mutex;
use AMF\Mutex\MutexInterface;
/**
* Adapter to adapt mutex to current context.
*
* @author Amine Fattouch <amine.fattouch@gmail.com>
*/
class MutexAdapter
{
/**
* @var MutexInterface
*/
protected $mutex;
/**
* @var integer
*/
protected $attemptTotal;
/**
* @var integer
*/
protected $wait;
/**
* @var string
*/
protected $prefix;
/**
*
* @param MutexInterface $mutex
* @param integer $attemptTotal
* @param integer $wait
* @param string $prefix
*/
public function __construct(MutexInterface $mutex, $attemptTotal = 10, $wait = 1, $prefix = 'worker_mutex')
{
$this->mutex = $mutex;
$this->attemptTotal = $attemptTotal;
$this->wait = $wait;
$this->prefix = $prefix;
}
/**
* Acquires access to Semaphore.
*
* @param string $key
* @param integer $ttl
*
* @return string
*/
public function acquire($key, $ttl = 60)
{
$generatedKey = $this->generateKey($key);
$attemptTotal = $this->attemptTotal;
$mutex = $this->mutex;
while ($attemptTotal > 0 && !$acquired = $mutex->acquire($generatedKey, $ttl)) {
$attemptTotal --;
sleep($this->wait);
}
if (isset($acquired) === false) {
throw new \RuntimeException('Can\'t acquire the mutex. it\'s already taken by another process.');
}
return $generatedKey;
}
/**
* Releases access to Semaphore.
*
* @param string $key
*/
public function release($key)
{
$generatedKey = $this->generateKey($key);
if ($this->mutex->release($generatedKey) === false) {
throw new \RuntimeException('Can\'t relase the mutex. you must acquire it first.');
}
}
/**
* Generates a key with prefix.
*
* @param string $key
*
* @return string
*/
protected function generateKey($key)
{
return $this->prefix.$key;
}
}