From 8dd597238d8f6bce72d1902e70ee99958b243df2 Mon Sep 17 00:00:00 2001 From: coderstephen Date: Fri, 10 Jul 2015 16:17:18 -0500 Subject: [PATCH] Semaphore handles can be serialized across contexts --- src/Semaphore.php | 67 ++++++++++++++++++++++++++++++++++++++--------- 1 file changed, 55 insertions(+), 12 deletions(-) diff --git a/src/Semaphore.php b/src/Semaphore.php index d0ded07..5605336 100644 --- a/src/Semaphore.php +++ b/src/Semaphore.php @@ -1,33 +1,53 @@ key = abs(crc32(spl_object_hash($this))); - $this->identifier = sem_get($this->key, $max, $permissions); + $this->maxLocks = $maxLocks; + $this->handle = sem_get($this->key, $maxLocks, $permissions, 0); - if ($this->identifier === false) { + if ($this->handle === false) { throw new SemaphoreException('Failed to create the semaphore.'); } } - public function __destruct() + /** + * Gets the maximum number of locks. + * + * @return int The maximum number of locks. + */ + public function getMaxLocks() { - $this->remove(); + return $this->maxLocks; } /** @@ -37,7 +57,7 @@ class Semaphore */ public function lock() { - if (!sem_acquire($this->identifier)) { + if (!sem_acquire($this->handle)) { throw new SemaphoreException('Failed to lock the semaphore.'); } } @@ -47,7 +67,7 @@ class Semaphore */ public function unlock() { - if (!sem_release($this->identifier)) { + if (!sem_release($this->handle)) { throw new SemaphoreException('Failed to unlock the semaphore.'); } } @@ -55,9 +75,9 @@ class Semaphore /** * Removes the semaphore if it still exists. */ - public function remove() + public function destroy() { - if (!@sem_remove($this->identifier)) { + if (!@sem_remove($this->handle)) { $error = error_get_last(); if ($error['type'] !== E_WARNING) { @@ -65,4 +85,27 @@ class Semaphore } } } + + /** + * Serializes the semaphore. + * + * @return string The serialized semaphore. + */ + public function serialize() + { + return serialize([$this->key, $this->maxLocks]); + } + + /** + * Unserializes a serialized semaphore. + * + * @param string $serialized The serialized semaphore. + */ + public function unserialize($serialized) + { + // Get the semaphore key and attempt to re-connect to the semaphore in + // memory. + list($this->key, $this->maxLocks) = unserialize($serialized); + $this->handle = sem_get($this->key, $maxLocks); + } }