1
0
mirror of https://github.com/danog/parallel.git synced 2024-12-02 17:52:14 +01:00
parallel/lib/Worker/functions.php

79 lines
1.6 KiB
PHP
Raw Normal View History

2016-08-22 06:40:48 +02:00
<?php declare(strict_types = 1);
2016-08-23 23:47:40 +02:00
namespace Amp\Parallel\Worker;
2016-11-15 00:43:44 +01:00
use Interop\Async\Promise;
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 {
static $instance;
2016-08-18 18:04:48 +02:00
if (null !== $pool) {
$instance = $pool;
} elseif (null === $instance) {
2016-08-23 01:25:19 +02:00
$instance = new DefaultPool;
}
2016-08-18 18:04:48 +02:00
if (!$instance->isRunning()) {
$instance->start();
}
2016-08-18 18:04:48 +02:00
return $instance;
}
/**
* 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
*
2016-11-15 00:43:44 +01:00
* @return \Interop\Async\Promise<mixed>
2016-08-18 18:04:48 +02:00
*/
2016-11-15 00:43:44 +01:00
function enqueue(Task $task): Promise {
2016-08-18 18:04:48 +02:00
return pool()->enqueue($task);
}
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 {
static $instance;
2016-08-18 18:04:48 +02:00
if (null !== $factory) {
$instance = $factory;
} elseif (null === $instance) {
2016-08-23 01:25:19 +02:00
$instance = new DefaultWorkerFactory;
2016-01-11 16:32:06 +01:00
}
2016-08-18 18:04:48 +02:00
return $instance;
}
/**
* 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 {
return pool()->get();
}