1
0
mirror of https://github.com/danog/parallel.git synced 2024-12-03 10:07:49 +01:00
parallel/lib/Worker/functions.php

94 lines
1.9 KiB
PHP
Raw Normal View History

2016-12-30 02:16:04 +01:00
<?php
2016-08-23 23:47:40 +02:00
namespace Amp\Parallel\Worker;
2017-05-18 09:51:31 +02:00
use Amp\Loop;
use Amp\Promise;
2017-01-11 18:52:12 +01:00
const LOOP_POOL_IDENTIFIER = Pool::class;
const LOOP_FACTORY_IDENTIFIER = WorkerFactory::class;
2015-08-29 07:41:00 +02:00
2016-08-18 18:04:48 +02:00
/**
* Returns the global worker pool for the current context.
*
2016-08-23 23:47:40 +02:00
* @param \Amp\Parallel\Worker\Pool|null $pool A worker pool instance.
2016-08-18 18:04:48 +02:00
*
2016-08-23 23:47:40 +02:00
* @return \Amp\Parallel\Worker\Pool The global worker pool instance.
2016-08-18 18:04:48 +02:00
*/
function pool(Pool $pool = null): Pool {
2017-01-11 18:52:12 +01:00
if ($pool === null) {
$pool = Loop::getState(LOOP_POOL_IDENTIFIER);
if ($pool) {
return $pool;
}
2017-01-11 18:52:12 +01:00
$pool = new DefaultPool;
}
2017-01-11 18:52:12 +01:00
Loop::setState(LOOP_POOL_IDENTIFIER, $pool);
return $pool;
2016-08-18 18:04:48 +02:00
}
/**
* Enqueues a task to be executed by the global worker pool.
*
2016-08-23 23:47:40 +02:00
* @param \Amp\Parallel\Worker\Task $task The task to enqueue.
2016-08-18 18:04:48 +02:00
*
* @return \Amp\Promise<mixed>
2016-08-18 18:04:48 +02:00
*/
2016-11-15 00:43:44 +01:00
function enqueue(Task $task): Promise {
2017-07-18 05:54:14 +02:00
$pool = pool();
if (!$pool->isRunning()) {
$pool->start();
}
return $pool->enqueue($task);
2016-08-18 18:04:48 +02:00
}
2016-01-11 16:32:06 +01:00
2016-08-18 18:04:48 +02:00
/**
* Creates a worker using the global worker factory.
*
2016-08-23 23:47:40 +02:00
* @return \Amp\Parallel\Worker\Worker
2016-08-18 18:04:48 +02:00
*/
function create(): Worker {
$worker = factory()->create();
$worker->start();
return $worker;
}
2016-08-18 18:04:48 +02:00
/**
* Gets or sets the global worker factory.
*
2016-08-23 23:47:40 +02:00
* @param \Amp\Parallel\Worker\WorkerFactory|null $factory
2016-08-18 18:04:48 +02:00
*
2016-08-23 23:47:40 +02:00
* @return \Amp\Parallel\Worker\WorkerFactory
2016-08-18 18:04:48 +02:00
*/
function factory(WorkerFactory $factory = null): WorkerFactory {
2017-01-11 18:52:12 +01:00
if ($factory === null) {
$factory = Loop::getState(LOOP_FACTORY_IDENTIFIER);
if ($factory) {
return $factory;
}
2017-01-11 18:52:12 +01:00
$factory = new DefaultWorkerFactory;
2016-01-11 16:32:06 +01:00
}
2017-01-11 18:52:12 +01:00
Loop::setState(LOOP_FACTORY_IDENTIFIER, $factory);
return $factory;
2016-08-18 18:04:48 +02:00
}
/**
* Gets a worker from the global worker pool.
*
2016-08-23 23:47:40 +02:00
* @return \Amp\Parallel\Worker\Worker
2016-08-18 18:04:48 +02:00
*/
function get(): Worker {
2017-07-18 05:54:14 +02:00
$pool = pool();
if (!$pool->isRunning()) {
$pool->start();
}
return $pool->get();
}