From 97112e4dd089eaa21a7c473725b9b7cce36d404d Mon Sep 17 00:00:00 2001 From: Anatol Belski Date: Fri, 15 Sep 2017 10:36:13 +0200 Subject: [PATCH] Refactor lock also wrt shared/exclusive --- lib/php/libsdk/SDK/Lock.php | 39 ++++++++++++++++++++++--------------- 1 file changed, 23 insertions(+), 16 deletions(-) diff --git a/lib/php/libsdk/SDK/Lock.php b/lib/php/libsdk/SDK/Lock.php index 73a9a63..1f762a8 100644 --- a/lib/php/libsdk/SDK/Lock.php +++ b/lib/php/libsdk/SDK/Lock.php @@ -17,8 +17,6 @@ class Lock $hash = hash("sha256", $tag); $this->fn = Config::getTmpDir() . DIRECTORY_SEPARATOR . $hash . ".lock"; - $this->fd = fopen($this->fn, "wb"); - if ($auto) { if ($autoShared) { $this->shared(); @@ -28,6 +26,15 @@ class Lock } }/*}}}*/ + public function __destruct() + {/*{{{*/ + $this->unlock(); + /* We don't really know no one else waits on the same lock yet.*/ + /*if (file_exists($this->fn) && !$this->shared) { + @unlink($this->fn); + }*/ + }/*}}}*/ + public function shared(bool $block = false) : bool {/*{{{*/ $flags = LOCK_SH; @@ -55,16 +62,27 @@ class Lock return true; } - $this->locked = flock($this->fd, $flags, $this->wouldBlock); $this->shared = $flags & LOCK_SH; + if ($this->shared) { + $this->fd = fopen($this->fn, "rb"); + } else { + $this->fd = fopen($this->fn, "wb"); + } + $this->locked = flock($this->fd, $flags, $this->wouldBlock); return $this->locked; }/*}}}*/ public function unlock() : bool {/*{{{*/ - if ($this->locked) { - return $this->doLock(LOCK_UN); + if (!$this->locked) { + return true; } + + $this->doLock(LOCK_UN); + + fclose($this->fd); + $this->fd = NULL; + return $this->locked; }/*}}}*/ @@ -77,17 +95,6 @@ class Lock {/*{{{*/ return 1 === $this->wouldBlock; }/*}}}*/ - - public function __destruct() - {/*{{{*/ - $this->unlock(); - fclose($this->fd); - /* We don't really know no one else waits on the same lock yet.*/ - /*if (file_exists($this->fn) && !$this->shared) { - @unlink($this->fn); - }*/ - }/*}}}*/ - } /*