Skip to content

Commit 97112e4

Browse files
committed
Refactor lock also wrt shared/exclusive
1 parent 098f645 commit 97112e4

File tree

1 file changed

+23
-16
lines changed

1 file changed

+23
-16
lines changed

lib/php/libsdk/SDK/Lock.php

+23-16
Original file line numberDiff line numberDiff line change
@@ -17,8 +17,6 @@ public function __construct(string $tag, bool $auto = true, bool $autoShared = f
1717
$hash = hash("sha256", $tag);
1818
$this->fn = Config::getTmpDir() . DIRECTORY_SEPARATOR . $hash . ".lock";
1919

20-
$this->fd = fopen($this->fn, "wb");
21-
2220
if ($auto) {
2321
if ($autoShared) {
2422
$this->shared();
@@ -28,6 +26,15 @@ public function __construct(string $tag, bool $auto = true, bool $autoShared = f
2826
}
2927
}/*}}}*/
3028

29+
public function __destruct()
30+
{/*{{{*/
31+
$this->unlock();
32+
/* We don't really know no one else waits on the same lock yet.*/
33+
/*if (file_exists($this->fn) && !$this->shared) {
34+
@unlink($this->fn);
35+
}*/
36+
}/*}}}*/
37+
3138
public function shared(bool $block = false) : bool
3239
{/*{{{*/
3340
$flags = LOCK_SH;
@@ -55,16 +62,27 @@ protected function doLock(int $flags = LOCK_EX) : bool
5562
return true;
5663
}
5764

58-
$this->locked = flock($this->fd, $flags, $this->wouldBlock);
5965
$this->shared = $flags & LOCK_SH;
66+
if ($this->shared) {
67+
$this->fd = fopen($this->fn, "rb");
68+
} else {
69+
$this->fd = fopen($this->fn, "wb");
70+
}
71+
$this->locked = flock($this->fd, $flags, $this->wouldBlock);
6072
return $this->locked;
6173
}/*}}}*/
6274

6375
public function unlock() : bool
6476
{/*{{{*/
65-
if ($this->locked) {
66-
return $this->doLock(LOCK_UN);
77+
if (!$this->locked) {
78+
return true;
6779
}
80+
81+
$this->doLock(LOCK_UN);
82+
83+
fclose($this->fd);
84+
$this->fd = NULL;
85+
6886
return $this->locked;
6987
}/*}}}*/
7088

@@ -77,17 +95,6 @@ public function wouldBlock() : bool
7795
{/*{{{*/
7896
return 1 === $this->wouldBlock;
7997
}/*}}}*/
80-
81-
public function __destruct()
82-
{/*{{{*/
83-
$this->unlock();
84-
fclose($this->fd);
85-
/* We don't really know no one else waits on the same lock yet.*/
86-
/*if (file_exists($this->fn) && !$this->shared) {
87-
@unlink($this->fn);
88-
}*/
89-
}/*}}}*/
90-
9198
}
9299

93100
/*

0 commit comments

Comments
 (0)