-
Notifications
You must be signed in to change notification settings - Fork 1
/
mutex.php
39 lines (34 loc) · 933 Bytes
/
mutex.php
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
<?php
class Mutex {
const TIMEOUT = 10; // Time-out in seconds
var $lockName = '';
var $fileHandle = null;
function __construct($lockName, $lock=1) {
$this->lockName = $lockName . '.mutex';
for ($i = 0; $i <= self::TIMEOUT; $i++) {
if ($this->getLock()) return true;
sleep(1); // wait for the mutex to be free
}
}
function __destruct() {
$this->releaseLock();
// unlink($this->lockName);
}
function getFileHandle() {
if ($this->fileHandle == null) {
$this->fileHandle = fopen($this->lockName, 'c');
}
return $this->fileHandle;
}
function getLock() {
return flock($this->getFileHandle(), LOCK_EX | LOCK_NB);
}
function releaseLock() {
if ($this->fileHandle != null) {
$success = flock($this->fileHandle, LOCK_UN | LOCK_NB);
fclose($this->getFileHandle());
$this->fileHandle = null;
}
return $success;
}
}