2016-12-29 19:16:04 -06:00
|
|
|
<?php
|
2015-08-21 22:41:38 -05:00
|
|
|
|
2016-08-23 16:47:40 -05:00
|
|
|
namespace Amp\Parallel\Worker;
|
2016-08-18 11:04:48 -05:00
|
|
|
|
2017-11-29 15:01:32 -06:00
|
|
|
use Amp\Parallel\Context\Thread;
|
2017-12-10 16:43:19 -06:00
|
|
|
use Amp\Parallel\Sync\Channel;
|
2017-05-18 09:51:31 +02:00
|
|
|
use Amp\Promise;
|
2015-08-21 22:41:38 -05:00
|
|
|
|
|
|
|
/**
|
|
|
|
* A worker thread that executes task objects.
|
|
|
|
*/
|
2018-10-26 18:29:45 -05:00
|
|
|
final class WorkerThread extends TaskWorker
|
2018-10-07 09:50:45 -05:00
|
|
|
{
|
2017-07-26 01:02:34 -05:00
|
|
|
/**
|
|
|
|
* @param string $envClassName Name of class implementing \Amp\Parallel\Worker\Environment to instigate.
|
|
|
|
* Defaults to \Amp\Parallel\Worker\BasicEnvironment.
|
|
|
|
*/
|
2018-10-07 09:50:45 -05:00
|
|
|
public function __construct(string $envClassName = BasicEnvironment::class)
|
|
|
|
{
|
2017-12-10 16:43:19 -06:00
|
|
|
parent::__construct(new Thread(function (Channel $channel, string $className): Promise {
|
2017-11-30 23:58:41 -06:00
|
|
|
if (!\class_exists($className)) {
|
|
|
|
throw new \Error(\sprintf("Invalid environment class name '%s'", $className));
|
2017-07-26 01:02:34 -05:00
|
|
|
}
|
|
|
|
|
2017-11-30 23:58:41 -06:00
|
|
|
if (!\is_subclass_of($className, Environment::class)) {
|
2017-07-26 01:02:34 -05:00
|
|
|
throw new \Error(\sprintf("The class '%s' does not implement '%s'", $className, Environment::class));
|
|
|
|
}
|
|
|
|
|
2017-11-30 23:58:41 -06:00
|
|
|
$environment = new $className;
|
2017-07-26 01:02:34 -05:00
|
|
|
|
|
|
|
if (!\defined("AMP_WORKER")) {
|
2019-02-17 23:50:41 -06:00
|
|
|
\define("AMP_WORKER", \AMP_CONTEXT);
|
2017-07-26 01:02:34 -05:00
|
|
|
}
|
|
|
|
|
2017-12-10 16:43:19 -06:00
|
|
|
$runner = new TaskRunner($channel, $environment);
|
2016-08-18 11:04:48 -05:00
|
|
|
return $runner->run();
|
2017-07-26 01:02:34 -05:00
|
|
|
}, $envClassName));
|
2015-08-21 22:41:38 -05:00
|
|
|
}
|
|
|
|
}
|