1
0
mirror of https://github.com/danog/parallel.git synced 2024-12-04 10:38:30 +01:00
parallel/lib/Threading/Parcel.php

102 lines
2.3 KiB
PHP
Raw Normal View History

2016-08-22 06:40:48 +02:00
<?php declare(strict_types = 1);
2016-08-23 23:47:40 +02:00
namespace Amp\Parallel\Threading;
2016-08-18 18:04:48 +02:00
use Amp\Coroutine;
2016-08-23 23:47:40 +02:00
use Amp\Parallel\Sync\Parcel as SyncParcel;
2016-08-18 18:04:48 +02:00
use Interop\Async\Awaitable;
/**
* A thread-safe container that shares a value between multiple threads.
*/
2016-08-18 18:04:48 +02:00
class Parcel implements SyncParcel {
2015-09-03 00:23:22 +02:00
/**
2016-08-23 23:47:40 +02:00
* @var \Amp\Parallel\Threading\Mutex
2015-09-03 00:23:22 +02:00
*/
private $mutex;
2015-09-03 00:23:22 +02:00
/**
2016-08-23 23:47:40 +02:00
* @var \Amp\Parallel\Threading\Internal\Storage
2015-09-03 00:23:22 +02:00
*/
private $storage;
/**
* Creates a new shared object container.
*
* @param mixed $value The value to store in the container.
*/
2016-08-19 00:36:58 +02:00
public function __construct($value) {
2015-09-04 01:11:58 +02:00
$this->init($value);
}
/**
* @param mixed $value
*/
2016-08-19 00:36:58 +02:00
private function init($value) {
2016-08-23 01:25:19 +02:00
$this->mutex = new Mutex;
2015-09-04 01:11:58 +02:00
$this->storage = new Internal\Storage($value);
}
/**
* {@inheritdoc}
*/
2016-08-18 18:04:48 +02:00
public function unwrap() {
return $this->storage->get();
}
/**
* {@inheritdoc}
*/
2016-08-18 18:04:48 +02:00
protected function wrap($value) {
$this->storage->set($value);
}
2016-08-18 18:04:48 +02:00
/**
* @return \Interop\Async\Awaitable
*/
public function synchronized(callable $callback): Awaitable {
return new Coroutine($this->doSynchronized($callback));
}
/**
* @coroutine
*
2015-09-04 01:11:58 +02:00
* Asynchronously invokes a callable while maintaining an exclusive lock on the container.
*
2015-09-04 01:11:58 +02:00
* @param callable<mixed> $callback The function to invoke. The value in the container will be passed as the first
* argument.
*
* @return \Generator
*/
2016-08-18 18:04:48 +02:00
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->mutex->acquire();
try {
$value = $this->unwrap();
2016-08-18 18:04:48 +02:00
$result = $callback($value);
if ($result instanceof \Generator) {
$result = new Coroutine($result);
}
if ($result instanceof Awaitable) {
yield $result;
}
$this->wrap(null === $result ? $value : $result);
} finally {
$lock->release();
}
2016-01-23 07:00:56 +01:00
return $result;
}
/**
* {@inheritdoc}
*/
2016-08-18 18:04:48 +02:00
public function __clone() {
2015-09-04 01:11:58 +02:00
$this->init($this->unwrap());
}
}