2015-08-19 22:56:00 +02:00
|
|
|
<?php
|
2015-08-29 08:40:10 +02:00
|
|
|
namespace Icicle\Concurrent\Threading;
|
|
|
|
|
|
|
|
use Icicle\Concurrent\Sync\ParcelInterface;
|
2015-08-19 22:56:00 +02:00
|
|
|
|
|
|
|
/**
|
|
|
|
* A thread-safe container that shares a value between multiple threads.
|
|
|
|
*/
|
2015-08-29 08:40:10 +02:00
|
|
|
class Parcel implements ParcelInterface
|
2015-08-19 22:56:00 +02:00
|
|
|
{
|
|
|
|
private $mutex;
|
2015-08-29 08:40:10 +02:00
|
|
|
private $storage;
|
2015-08-19 22:56:00 +02:00
|
|
|
|
|
|
|
/**
|
|
|
|
* Creates a new shared object container.
|
|
|
|
*
|
|
|
|
* @param mixed $value The value to store in the container.
|
|
|
|
*/
|
|
|
|
public function __construct($value)
|
|
|
|
{
|
2015-08-29 08:40:10 +02:00
|
|
|
$this->mutex = new Mutex();
|
|
|
|
$this->storage = new Internal\Storage();
|
2015-08-31 11:21:44 +02:00
|
|
|
$this->storage->set($value);
|
2015-08-19 22:56:00 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
2015-08-20 21:13:01 +02:00
|
|
|
* {@inheritdoc}
|
2015-08-19 22:56:00 +02:00
|
|
|
*/
|
2015-08-20 21:13:01 +02:00
|
|
|
public function unwrap()
|
2015-08-19 22:56:00 +02:00
|
|
|
{
|
2015-08-29 08:40:10 +02:00
|
|
|
return $this->storage->get();
|
2015-08-19 22:56:00 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
2015-08-20 21:13:01 +02:00
|
|
|
* {@inheritdoc}
|
2015-08-19 22:56:00 +02:00
|
|
|
*/
|
2015-08-20 21:13:01 +02:00
|
|
|
public function wrap($value)
|
2015-08-19 22:56:00 +02:00
|
|
|
{
|
2015-08-29 08:40:10 +02:00
|
|
|
$this->storage->set($value);
|
2015-08-19 22:56:00 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
2015-08-29 08:40:10 +02:00
|
|
|
* @coroutine
|
|
|
|
*
|
2015-08-19 22:56:00 +02:00
|
|
|
* Asynchronously invokes a callable while maintaining an exclusive lock on
|
|
|
|
* the container.
|
|
|
|
*
|
|
|
|
* @param callable<mixed> $function The function to invoke. The value in the
|
|
|
|
* container will be passed as the first
|
|
|
|
* argument.
|
|
|
|
*
|
|
|
|
* @return \Generator
|
|
|
|
*/
|
|
|
|
public function synchronized(callable $function)
|
|
|
|
{
|
2015-08-29 08:40:10 +02:00
|
|
|
/** @var \Icicle\Concurrent\Sync\Lock $lock */
|
2015-08-19 22:56:00 +02:00
|
|
|
$lock = (yield $this->mutex->acquire());
|
|
|
|
|
|
|
|
try {
|
2015-08-29 08:40:10 +02:00
|
|
|
$value = (yield $function($this->storage->get()));
|
|
|
|
$this->storage->set($value);
|
2015-08-19 22:56:00 +02:00
|
|
|
} finally {
|
|
|
|
$lock->release();
|
|
|
|
}
|
2015-08-29 08:40:10 +02:00
|
|
|
|
|
|
|
yield $value;
|
2015-08-19 22:56:00 +02:00
|
|
|
}
|
2015-08-20 21:13:01 +02:00
|
|
|
|
|
|
|
/**
|
|
|
|
* {@inheritdoc}
|
|
|
|
*/
|
|
|
|
public function __clone()
|
|
|
|
{
|
2015-08-29 08:40:10 +02:00
|
|
|
$this->storage = clone $this->storage;
|
2015-08-20 21:13:01 +02:00
|
|
|
$this->mutex = clone $this->mutex;
|
|
|
|
}
|
2015-08-19 22:56:00 +02:00
|
|
|
}
|