2016-12-30 02:16:04 +01:00
|
|
|
<?php
|
2015-12-05 06:50:32 +01:00
|
|
|
|
2016-08-23 23:47:40 +02:00
|
|
|
namespace Amp\Parallel\Sync;
|
2016-08-18 18:04:48 +02:00
|
|
|
|
|
|
|
use Amp\Coroutine;
|
2016-08-23 23:47:40 +02:00
|
|
|
use Amp\Parallel\SharedMemoryException;
|
2017-01-09 18:11:25 +01:00
|
|
|
use AsyncInterop\Promise;
|
2015-12-05 06:50:32 +01:00
|
|
|
|
|
|
|
/**
|
|
|
|
* A container object for sharing a value across contexts.
|
|
|
|
*
|
|
|
|
* A shared object is a container that stores an object inside shared memory.
|
|
|
|
* The object can be accessed and mutated by any thread or process. The shared
|
|
|
|
* object handle itself is serializable and can be sent to any thread or process
|
|
|
|
* to give access to the value that is shared in the container.
|
|
|
|
*
|
|
|
|
* Because each shared object uses its own shared memory segment, it is much
|
|
|
|
* more efficient to store a larger object containing many values inside a
|
|
|
|
* single shared container than to use many small shared containers.
|
|
|
|
*
|
|
|
|
* Note that accessing a shared object is not atomic. Access to a shared object
|
|
|
|
* should be protected with a mutex to preserve data integrity.
|
|
|
|
*
|
|
|
|
* When used with forking, the object must be created prior to forking for both
|
|
|
|
* processes to access the synchronized object.
|
|
|
|
*
|
|
|
|
* @see http://php.net/manual/en/book.shmop.php The shared memory extension.
|
|
|
|
* @see http://man7.org/linux/man-pages/man2/shmctl.2.html How shared memory works on Linux.
|
|
|
|
* @see https://msdn.microsoft.com/en-us/library/ms810613.aspx How shared memory works on Windows.
|
|
|
|
*/
|
2016-08-18 18:04:48 +02:00
|
|
|
class SharedMemoryParcel implements Parcel, \Serializable {
|
2016-08-26 17:10:03 +02:00
|
|
|
/** @var int The byte offset to the start of the object data in memory. */
|
2015-12-05 06:50:32 +01:00
|
|
|
const MEM_DATA_OFFSET = 7;
|
|
|
|
|
|
|
|
// A list of valid states the object can be in.
|
|
|
|
const STATE_UNALLOCATED = 0;
|
|
|
|
const STATE_ALLOCATED = 1;
|
|
|
|
const STATE_MOVED = 2;
|
|
|
|
const STATE_FREED = 3;
|
|
|
|
|
2016-08-26 17:10:03 +02:00
|
|
|
/** @var int The shared memory segment key. */
|
2015-12-05 06:50:32 +01:00
|
|
|
private $key;
|
|
|
|
|
2016-08-26 17:10:03 +02:00
|
|
|
/** @var PosixSemaphore A semaphore for synchronizing on the parcel. */
|
2015-12-05 06:50:32 +01:00
|
|
|
private $semaphore;
|
|
|
|
|
2016-08-26 17:10:03 +02:00
|
|
|
/** @var int An open handle to the shared memory segment. */
|
2015-12-05 06:50:32 +01:00
|
|
|
private $handle;
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Creates a new local object container.
|
|
|
|
*
|
|
|
|
* The object given will be assigned a new object ID and will have a
|
|
|
|
* reference to it stored in memory local to the thread.
|
|
|
|
*
|
|
|
|
* @param mixed $value The value to store in the container.
|
|
|
|
* @param int $size The number of bytes to allocate for the object.
|
|
|
|
* If not specified defaults to 16384 bytes.
|
|
|
|
* @param int $permissions The access permissions to set for the object.
|
|
|
|
* If not specified defaults to 0600.
|
|
|
|
*/
|
2016-08-18 18:04:48 +02:00
|
|
|
public function __construct($value, int $size = 16384, int $permissions = 0600) {
|
|
|
|
if (!\extension_loaded("shmop")) {
|
|
|
|
throw new \Error(__CLASS__ . " requires the shmop extension.");
|
2015-12-05 06:50:32 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
$this->init($value, $size, $permissions);
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* @param mixed $value
|
|
|
|
* @param int $size
|
|
|
|
* @param int $permissions
|
|
|
|
*/
|
2016-08-18 18:04:48 +02:00
|
|
|
private function init($value, int $size = 16384, int $permissions = 0600) {
|
|
|
|
$this->key = \abs(\crc32(\spl_object_hash($this)));
|
2015-12-05 06:50:32 +01:00
|
|
|
$this->memOpen($this->key, 'n', $permissions, $size + self::MEM_DATA_OFFSET);
|
|
|
|
$this->setHeader(self::STATE_ALLOCATED, 0, $permissions);
|
|
|
|
$this->wrap($value);
|
|
|
|
|
|
|
|
$this->semaphore = new PosixSemaphore(1);
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Checks if the object has been freed.
|
|
|
|
*
|
|
|
|
* Note that this does not check if the object has been destroyed; it only
|
|
|
|
* checks if this handle has freed its reference to the object.
|
|
|
|
*
|
|
|
|
* @return bool True if the object is freed, otherwise false.
|
|
|
|
*/
|
2016-08-18 18:04:48 +02:00
|
|
|
public function isFreed(): bool {
|
2015-12-05 06:50:32 +01:00
|
|
|
// If we are no longer connected to the memory segment, check if it has
|
|
|
|
// been invalidated.
|
|
|
|
if ($this->handle !== null) {
|
|
|
|
$this->handleMovedMemory();
|
|
|
|
$header = $this->getHeader();
|
|
|
|
return $header['state'] === static::STATE_FREED;
|
|
|
|
}
|
|
|
|
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* {@inheritdoc}
|
|
|
|
*/
|
2016-08-18 18:04:48 +02:00
|
|
|
public function unwrap() {
|
2015-12-05 06:50:32 +01:00
|
|
|
if ($this->isFreed()) {
|
|
|
|
throw new SharedMemoryException('The object has already been freed.');
|
|
|
|
}
|
|
|
|
|
|
|
|
$header = $this->getHeader();
|
|
|
|
|
|
|
|
// Make sure the header is in a valid state and format.
|
|
|
|
if ($header['state'] !== self::STATE_ALLOCATED || $header['size'] <= 0) {
|
|
|
|
throw new SharedMemoryException('Shared object memory is corrupt.');
|
|
|
|
}
|
|
|
|
|
|
|
|
// Read the actual value data from memory and unserialize it.
|
|
|
|
$data = $this->memGet(self::MEM_DATA_OFFSET, $header['size']);
|
2016-08-18 18:04:48 +02:00
|
|
|
return \unserialize($data);
|
2015-12-05 06:50:32 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* If the value requires more memory to store than currently allocated, a
|
|
|
|
* new shared memory segment will be allocated with a larger size to store
|
|
|
|
* the value in. The previous memory segment will be cleaned up and marked
|
|
|
|
* for deletion. Other processes and threads will be notified of the new
|
|
|
|
* memory segment on the next read attempt. Once all running processes and
|
|
|
|
* threads disconnect from the old segment, it will be freed by the OS.
|
|
|
|
*/
|
2016-08-18 18:04:48 +02:00
|
|
|
protected function wrap($value) {
|
2015-12-05 06:50:32 +01:00
|
|
|
if ($this->isFreed()) {
|
|
|
|
throw new SharedMemoryException('The object has already been freed.');
|
|
|
|
}
|
|
|
|
|
2016-08-18 18:04:48 +02:00
|
|
|
$serialized = \serialize($value);
|
|
|
|
$size = \strlen($serialized);
|
2015-12-05 06:50:32 +01:00
|
|
|
$header = $this->getHeader();
|
|
|
|
|
|
|
|
/* If we run out of space, we need to allocate a new shared memory
|
|
|
|
segment that is larger than the current one. To coordinate with other
|
|
|
|
processes, we will leave a message in the old segment that the segment
|
|
|
|
has moved and along with the new key. The old segment will be discarded
|
|
|
|
automatically after all other processes notice the change and close
|
|
|
|
the old handle.
|
|
|
|
*/
|
2016-08-18 18:04:48 +02:00
|
|
|
if (\shmop_size($this->handle) < $size + self::MEM_DATA_OFFSET) {
|
|
|
|
$this->key = $this->key < 0xffffffff ? $this->key + 1 : \mt_rand(0x10, 0xfffffffe);
|
2015-12-05 06:50:32 +01:00
|
|
|
$this->setHeader(self::STATE_MOVED, $this->key, 0);
|
|
|
|
|
|
|
|
$this->memDelete();
|
2016-08-18 18:04:48 +02:00
|
|
|
\shmop_close($this->handle);
|
2015-12-05 06:50:32 +01:00
|
|
|
|
|
|
|
$this->memOpen($this->key, 'n', $header['permissions'], $size * 2);
|
|
|
|
}
|
|
|
|
|
|
|
|
// Rewrite the header and the serialized value to memory.
|
|
|
|
$this->setHeader(self::STATE_ALLOCATED, $size, $header['permissions']);
|
|
|
|
$this->memSet(self::MEM_DATA_OFFSET, $serialized);
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* {@inheritdoc}
|
|
|
|
*/
|
2016-11-15 00:43:44 +01:00
|
|
|
public function synchronized(callable $callback): Promise {
|
2016-08-18 18:04:48 +02:00
|
|
|
return new Coroutine($this->doSynchronized($callback));
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* @coroutine
|
|
|
|
*
|
|
|
|
* @param callable $callback
|
|
|
|
*
|
|
|
|
* @return \Generator
|
|
|
|
*/
|
|
|
|
private function doSynchronized(callable $callback): \Generator {
|
2016-08-23 23:47:40 +02:00
|
|
|
/** @var \Amp\Parallel\Sync\Lock $lock */
|
2016-08-18 18:04:48 +02:00
|
|
|
$lock = yield $this->semaphore->acquire();
|
|
|
|
|
2015-12-05 06:50:32 +01:00
|
|
|
try {
|
|
|
|
$value = $this->unwrap();
|
2016-08-18 18:04:48 +02:00
|
|
|
$result = $callback($value);
|
|
|
|
|
|
|
|
if ($result instanceof \Generator) {
|
|
|
|
$result = new Coroutine($result);
|
|
|
|
}
|
|
|
|
|
2016-11-15 00:43:44 +01:00
|
|
|
if ($result instanceof Promise) {
|
2016-09-02 01:10:52 +02:00
|
|
|
$result = yield $result;
|
2016-08-18 18:04:48 +02:00
|
|
|
}
|
|
|
|
|
2015-12-05 06:50:32 +01:00
|
|
|
$this->wrap(null === $result ? $value : $result);
|
|
|
|
} finally {
|
|
|
|
$lock->release();
|
|
|
|
}
|
2016-08-18 18:04:48 +02:00
|
|
|
|
2016-01-23 07:00:56 +01:00
|
|
|
return $result;
|
2015-12-05 06:50:32 +01:00
|
|
|
}
|
2016-08-18 18:04:48 +02:00
|
|
|
|
|
|
|
|
2015-12-05 06:50:32 +01:00
|
|
|
/**
|
|
|
|
* Frees the shared object from memory.
|
|
|
|
*
|
|
|
|
* The memory containing the shared value will be invalidated. When all
|
|
|
|
* process disconnect from the object, the shared memory block will be
|
|
|
|
* destroyed by the OS.
|
|
|
|
*
|
|
|
|
* Calling `free()` on an object already freed will have no effect.
|
|
|
|
*/
|
2016-08-19 00:36:58 +02:00
|
|
|
public function free() {
|
2015-12-05 06:50:32 +01:00
|
|
|
if (!$this->isFreed()) {
|
|
|
|
// Invalidate the memory block by setting its state to FREED.
|
|
|
|
$this->setHeader(static::STATE_FREED, 0, 0);
|
|
|
|
|
|
|
|
// Request the block to be deleted, then close our local handle.
|
|
|
|
$this->memDelete();
|
2016-08-18 18:04:48 +02:00
|
|
|
\shmop_close($this->handle);
|
2015-12-05 06:50:32 +01:00
|
|
|
$this->handle = null;
|
|
|
|
|
|
|
|
$this->semaphore->free();
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Serializes the local object handle.
|
|
|
|
*
|
|
|
|
* Note that this does not serialize the object that is referenced, just the
|
|
|
|
* object handle.
|
|
|
|
*
|
|
|
|
* @return string The serialized object handle.
|
|
|
|
*/
|
2016-08-19 00:36:58 +02:00
|
|
|
public function serialize(): string {
|
2016-08-18 18:04:48 +02:00
|
|
|
return \serialize([$this->key, $this->semaphore]);
|
2015-12-05 06:50:32 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Unserializes the local object handle.
|
|
|
|
*
|
|
|
|
* @param string $serialized The serialized object handle.
|
|
|
|
*/
|
2016-08-19 00:36:58 +02:00
|
|
|
public function unserialize($serialized) {
|
2016-08-18 18:04:48 +02:00
|
|
|
list($this->key, $this->semaphore) = \unserialize($serialized);
|
2015-12-05 06:50:32 +01:00
|
|
|
$this->memOpen($this->key, 'w', 0, 0);
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* {@inheritdoc}
|
|
|
|
*/
|
2016-08-19 00:36:58 +02:00
|
|
|
public function __clone() {
|
2015-12-05 06:50:32 +01:00
|
|
|
$value = $this->unwrap();
|
|
|
|
$header = $this->getHeader();
|
|
|
|
$this->init($value, $header['size'], $header['permissions']);
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Gets information about the object for debugging purposes.
|
|
|
|
*
|
|
|
|
* @return array An array of debugging information.
|
|
|
|
*/
|
2016-08-19 00:36:58 +02:00
|
|
|
public function __debugInfo() {
|
2015-12-05 06:50:32 +01:00
|
|
|
if ($this->isFreed()) {
|
|
|
|
return [
|
|
|
|
'id' => $this->key,
|
|
|
|
'object' => null,
|
|
|
|
'freed' => true,
|
|
|
|
];
|
|
|
|
}
|
|
|
|
|
|
|
|
return [
|
|
|
|
'id' => $this->key,
|
|
|
|
'object' => $this->unwrap(),
|
|
|
|
'freed' => false,
|
|
|
|
];
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Updates the current memory segment handle, handling any moves made on the
|
|
|
|
* data.
|
|
|
|
*/
|
2016-08-19 00:36:58 +02:00
|
|
|
private function handleMovedMemory() {
|
2015-12-05 06:50:32 +01:00
|
|
|
// Read from the memory block and handle moved blocks until we find the
|
|
|
|
// correct block.
|
|
|
|
while (true) {
|
|
|
|
$header = $this->getHeader();
|
|
|
|
|
|
|
|
// If the state is STATE_MOVED, the memory is stale and has been moved
|
|
|
|
// to a new location. Move handle and try to read again.
|
|
|
|
if ($header['state'] !== self::STATE_MOVED) {
|
|
|
|
break;
|
|
|
|
}
|
|
|
|
|
2016-08-18 18:04:48 +02:00
|
|
|
\shmop_close($this->handle);
|
2015-12-05 06:50:32 +01:00
|
|
|
$this->key = $header['size'];
|
|
|
|
$this->memOpen($this->key, 'w', 0, 0);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Reads and returns the data header at the current memory segment.
|
|
|
|
*
|
|
|
|
* @return array An associative array of header data.
|
|
|
|
*/
|
2016-08-19 00:36:58 +02:00
|
|
|
private function getHeader(): array {
|
2015-12-05 06:50:32 +01:00
|
|
|
$data = $this->memGet(0, self::MEM_DATA_OFFSET);
|
2016-08-18 18:04:48 +02:00
|
|
|
return \unpack('Cstate/Lsize/Spermissions', $data);
|
2015-12-05 06:50:32 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Sets the header data for the current memory segment.
|
|
|
|
*
|
|
|
|
* @param int $state An object state.
|
|
|
|
* @param int $size The size of the stored data, or other value.
|
|
|
|
* @param int $permissions The permissions mask on the memory segment.
|
|
|
|
*/
|
2016-08-19 00:36:58 +02:00
|
|
|
private function setHeader(int $state, int $size, int $permissions) {
|
2016-08-18 18:04:48 +02:00
|
|
|
$header = \pack('CLS', $state, $size, $permissions);
|
2015-12-05 06:50:32 +01:00
|
|
|
$this->memSet(0, $header);
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Opens a shared memory handle.
|
|
|
|
*
|
|
|
|
* @param int $key The shared memory key.
|
|
|
|
* @param string $mode The mode to open the shared memory in.
|
|
|
|
* @param int $permissions Process permissions on the shared memory.
|
|
|
|
* @param int $size The size to crate the shared memory in bytes.
|
|
|
|
*/
|
2016-08-19 00:36:58 +02:00
|
|
|
private function memOpen(int $key, string $mode, int $permissions, int $size) {
|
2016-08-18 18:04:48 +02:00
|
|
|
$this->handle = @\shmop_open($key, $mode, $permissions, $size);
|
2015-12-05 06:50:32 +01:00
|
|
|
if ($this->handle === false) {
|
|
|
|
throw new SharedMemoryException('Failed to create shared memory block.');
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Reads binary data from shared memory.
|
|
|
|
*
|
|
|
|
* @param int $offset The offset to read from.
|
|
|
|
* @param int $size The number of bytes to read.
|
|
|
|
*
|
|
|
|
* @return string The binary data at the given offset.
|
|
|
|
*/
|
2016-08-19 00:36:58 +02:00
|
|
|
private function memGet(int $offset, int $size): string {
|
2016-08-18 18:04:48 +02:00
|
|
|
$data = \shmop_read($this->handle, $offset, $size);
|
2015-12-05 06:50:32 +01:00
|
|
|
if ($data === false) {
|
|
|
|
throw new SharedMemoryException('Failed to read from shared memory block.');
|
|
|
|
}
|
|
|
|
return $data;
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Writes binary data to shared memory.
|
|
|
|
*
|
|
|
|
* @param int $offset The offset to write to.
|
|
|
|
* @param string $data The binary data to write.
|
|
|
|
*/
|
2016-08-19 00:36:58 +02:00
|
|
|
private function memSet(int $offset, string $data) {
|
2016-08-18 18:04:48 +02:00
|
|
|
if (!\shmop_write($this->handle, $data, $offset)) {
|
2015-12-05 06:50:32 +01:00
|
|
|
throw new SharedMemoryException('Failed to write to shared memory block.');
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Requests the shared memory segment to be deleted.
|
|
|
|
*/
|
2016-08-19 00:36:58 +02:00
|
|
|
private function memDelete() {
|
2016-08-18 18:04:48 +02:00
|
|
|
if (!\shmop_delete($this->handle)) {
|
2015-12-05 06:50:32 +01:00
|
|
|
throw new SharedMemoryException('Failed to discard shared memory block.');
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|