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

59 lines
1.7 KiB
PHP
Raw Normal View History

2016-12-30 02:16:04 +01:00
<?php
2015-12-05 06:50:32 +01:00
2016-08-23 23:47:40 +02:00
namespace Amp\Parallel\Worker;
2016-08-18 18:04:48 +02:00
2019-02-13 21:19:01 +01:00
use Amp\Parallel\Context\Parallel;
2015-12-05 08:09:42 +01:00
2015-12-05 06:50:32 +01:00
/**
* The built-in worker factory type.
*/
2018-10-21 17:54:46 +02:00
final class DefaultWorkerFactory implements WorkerFactory
2018-10-07 16:50:45 +02:00
{
/** @var string */
private $className;
/**
* @param string $envClassName Name of class implementing \Amp\Parallel\Worker\Environment to instigate in each
* worker. Defaults to \Amp\Parallel\Worker\BasicEnvironment.
*
* @throws \Error If the given class name does not exist or does not implement \Amp\Parallel\Worker\Environment.
*/
2018-10-07 16:50:45 +02:00
public function __construct(string $envClassName = BasicEnvironment::class)
{
if (!\class_exists($envClassName)) {
throw new \Error(\sprintf("Invalid environment class name '%s'", $envClassName));
}
if (!\is_subclass_of($envClassName, Environment::class)) {
throw new \Error(\sprintf(
"The class '%s' does not implement '%s'",
$envClassName,
Environment::class
));
}
$this->className = $envClassName;
}
2015-12-05 06:50:32 +01:00
/**
* {@inheritdoc}
*
* The type of worker created depends on the extensions available. If multi-threading is enabled, a WorkerThread
* will be created. If threads are not available a WorkerProcess will be created.
2015-12-05 06:50:32 +01:00
*/
2018-10-07 16:50:45 +02:00
public function create(): Worker
{
2019-02-13 21:19:01 +01:00
if (Parallel::isSupported()) {
return new WorkerThread($this->className);
2015-12-05 06:50:32 +01:00
}
2019-02-13 21:19:01 +01:00
// Thread context is not use as pthreads is deprecated.
return new WorkerProcess(
$this->className,
[],
2017-12-08 18:45:13 +01:00
\getenv("AMP_PHP_BINARY") ?: (\defined("AMP_PHP_BINARY") ? \AMP_PHP_BINARY : null)
);
2015-12-05 06:50:32 +01:00
}
}