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

90 lines
1.9 KiB
PHP
Raw Normal View History

<?php
namespace Icicle\Concurrent\Threading;
2015-12-05 06:50:32 +01:00
use Icicle\Concurrent\Sync\Parcel as SyncParcel;
/**
* A thread-safe container that shares a value between multiple threads.
*/
2015-12-05 06:50:32 +01:00
class Parcel implements SyncParcel
{
2015-09-03 00:23:22 +02:00
/**
* @var \Icicle\Concurrent\Threading\Mutex
*/
private $mutex;
2015-09-03 00:23:22 +02:00
/**
* @var \Icicle\Concurrent\Threading\Internal\Storage
*/
private $storage;
/**
* Creates a new shared object container.
*
* @param mixed $value The value to store in the container.
*/
public function __construct($value)
2015-09-04 01:11:58 +02:00
{
$this->init($value);
}
/**
* @param mixed $value
*/
private function init($value)
{
$this->mutex = new Mutex();
2015-09-04 01:11:58 +02:00
$this->storage = new Internal\Storage($value);
}
/**
* {@inheritdoc}
*/
public function unwrap()
{
return $this->storage->get();
}
/**
* {@inheritdoc}
*/
protected function wrap($value)
{
$this->storage->set($value);
}
/**
* @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-01-23 07:00:56 +01:00
public function synchronized(callable $callback): \Generator
{
/** @var \Icicle\Concurrent\Sync\Lock $lock */
2016-01-23 07:00:56 +01:00
$lock = yield from $this->mutex->acquire();
try {
$value = $this->unwrap();
2016-01-23 07:00:56 +01:00
$result = yield $callback($value);
$this->wrap(null === $result ? $value : $result);
} finally {
$lock->release();
}
2016-01-23 07:00:56 +01:00
return $result;
}
/**
* {@inheritdoc}
*/
public function __clone()
{
2015-09-04 01:11:58 +02:00
$this->init($this->unwrap());
}
}