1
0
mirror of https://github.com/danog/parallel.git synced 2024-11-26 20:34:40 +01:00

Add ability to pass arguments to context function

This commit is contained in:
Aaron Piotrowski 2015-08-06 23:25:04 -05:00
parent 4d90dc5ca7
commit dc3cd5155e
3 changed files with 20 additions and 8 deletions

View File

@ -32,11 +32,12 @@ class ForkContext extends Synchronized implements ContextInterface
*/
private $function;
public function __construct(callable $function)
public function __construct(callable $function /* , ...$args */)
{
parent::__construct();
$this->function = $function;
$this->args = array_slice(func_get_args(), 1);
}
/**
@ -104,8 +105,9 @@ class ForkContext extends Synchronized implements ContextInterface
private function execute(Channel $channel)
{
try {
$function = $this->function;
$result = new ExitSuccess(yield $function($channel));
$result = new ExitSuccess(
yield call_user_func_array($this->function, array_merge([$channel], $this->args))
);
} catch (\Exception $exception) {
$result = new ExitFailure($exception);
}

View File

@ -22,6 +22,11 @@ class Thread extends \Thread
*/
private $function;
/**
* @var
*/
private $args;
private $prepared = false;
private $initialized = false;
@ -34,12 +39,14 @@ class Thread extends \Thread
* Creates a new thread object.
*
* @param callable $function The function to execute in the thread.
* @param mixed[]|null $args Arguments to pass to the function.
* @param string $autoloaderPath Path to autoloader include file.
*/
public function __construct(callable $function, $autoloaderPath = '')
public function __construct(callable $function, array $args = [], $autoloaderPath = '')
{
$this->autoloaderPath = $autoloaderPath;
$this->function = $function;
$this->args = $args;
}
/**
@ -111,8 +118,9 @@ class Thread extends \Thread
private function execute(Channel $channel)
{
try {
$function = $this->function;
$result = new ExitSuccess(yield $function($channel));
$result = new ExitSuccess(
yield call_user_func_array($this->function, array_merge([$channel], $this->args))
);
} catch (\Exception $exception) {
$result = new ExitFailure($exception);
}

View File

@ -31,9 +31,11 @@ class ThreadContext implements ContextInterface
*
* @param callable $function
*/
public function __construct(callable $function)
public function __construct(callable $function /* , ...$args */)
{
$this->thread = new Thread($function, $this->getComposerAutoloader());
$args = array_slice(func_get_args(), 1);
$this->thread = new Thread($function, $args, $this->getComposerAutoloader());
}
/**