From bb9aaad899c47e4eec49cbd444573e78d48a146a Mon Sep 17 00:00:00 2001 From: czaks Date: Sun, 8 May 2016 15:37:49 +0200 Subject: [PATCH] i forgot about a queue and a lock implementation --- inc/lock.php | 39 +++++++++++++++++++++++++++++++++++++++ inc/queue.php | 49 +++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 88 insertions(+) create mode 100644 inc/lock.php create mode 100644 inc/queue.php diff --git a/inc/lock.php b/inc/lock.php new file mode 100644 index 00000000..4fb2f5df --- /dev/null +++ b/inc/lock.php @@ -0,0 +1,39 @@ +f = fopen("tmp/locks/$key", "w"); + } + } + + // Get a shared lock + function get($nonblock = false) { global $config; + if ($config['lock']['enabled'] == 'fs') { + $wouldblock = false; + flock($this->f, LOCK_SH | ($nonblock ? LOCK_NB : 0), $wouldblock); + if ($nonblock && $wouldblock) return false; + } + return $this; + } + + // Get an exclusive lock + function get_ex($nonblock = false) { global $config; + if ($config['lock']['enabled'] == 'fs') { + $wouldblock = false; + flock($this->f, LOCK_EX | ($nonblock ? LOCK_NB : 0), $wouldblock); + if ($nonblock && $wouldblock) return false; + } + return $this; + } + + // Free a lock + function free() { global $config; + if ($config['lock']['enabled'] == 'fs') { + flock($this->f, LOCK_UN); + } + return $this; + } +} diff --git a/inc/queue.php b/inc/queue.php new file mode 100644 index 00000000..66305b3b --- /dev/null +++ b/inc/queue.php @@ -0,0 +1,49 @@ +lock = new Lock($key); + $key = str_replace('/', '::', $key); + $key = str_replace("\0", '', $key); + $this->key = "tmp/queue/$key/"; + } + } + + function push($str) { global $config; + if ($config['queue']['enabled'] == 'fs') { + $this->lock->get_ex(); + file_put_contents($this->key.microtime(true), $str); + $this->lock->free(); + } + return $this; + } + + function pop($n = 1) { global $config; + if ($config['queue']['enabled'] == 'fs') { + $this->lock->get_ex(); + $dir = opendir($this->key); + $paths = array(); + while ($n > 0) { + $path = readdir($dir); + if ($path === FALSE) break; + elseif ($path == '.' || $path == '..') continue; + else { $paths[] = $path; $n--; } + } + $out = array(); + foreach ($paths as $v) { + $out []= file_get_contents($this->key.$v); + unlink($this->key.$v); + } + $this->lock->free(); + return $out; + } + } +} + +// Don't use the constructor. Use the get_queue function. +$queues = array(); + +function get_queue($name) { global $queues; + return $queues[$name] = isset ($queues[$name]) ? $queues[$name] : new Queue($name); +}