2015-08-28 07:18:50 +02:00
|
|
|
<?php
|
|
|
|
namespace Icicle\Concurrent\Worker;
|
|
|
|
|
|
|
|
if (!function_exists(__NAMESPACE__ . '\pool')) {
|
|
|
|
/**
|
2015-08-29 03:30:53 +02:00
|
|
|
* Returns the global worker pool for the current context.
|
2015-08-28 07:18:50 +02:00
|
|
|
*
|
2015-12-05 06:50:32 +01:00
|
|
|
* @param \Icicle\Concurrent\Worker\Pool|null $pool A worker pool instance.
|
2015-08-28 19:04:04 +02:00
|
|
|
*
|
2015-12-05 06:50:32 +01:00
|
|
|
* @return \Icicle\Concurrent\Worker\Pool The global worker pool instance.
|
2015-08-28 07:18:50 +02:00
|
|
|
*/
|
2015-12-05 06:50:32 +01:00
|
|
|
function pool(Pool $pool = null)
|
2015-08-28 07:18:50 +02:00
|
|
|
{
|
|
|
|
static $instance;
|
|
|
|
|
2015-08-29 07:41:00 +02:00
|
|
|
if (null !== $pool) {
|
|
|
|
$instance = $pool;
|
|
|
|
} elseif (null === $instance) {
|
2015-12-05 06:50:32 +01:00
|
|
|
$instance = new DefaultPool();
|
2015-08-29 07:41:00 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
if (!$instance->isRunning()) {
|
2015-08-29 03:30:53 +02:00
|
|
|
$instance->start();
|
2015-08-28 07:18:50 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
return $instance;
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
2015-09-01 23:20:57 +02:00
|
|
|
* @coroutine
|
|
|
|
*
|
2015-08-28 07:18:50 +02:00
|
|
|
* Enqueues a task to be executed by the worker pool.
|
|
|
|
*
|
2015-12-05 06:50:32 +01:00
|
|
|
* @param \Icicle\Concurrent\Worker\Task $task The task to enqueue.
|
2015-08-28 07:18:50 +02:00
|
|
|
*
|
2015-09-01 23:20:57 +02:00
|
|
|
* @return \Generator
|
2015-08-28 07:18:50 +02:00
|
|
|
*
|
|
|
|
* @resolve mixed The return value of the task.
|
|
|
|
*/
|
2015-12-05 06:50:32 +01:00
|
|
|
function enqueue(Task $task)
|
2015-08-28 07:18:50 +02:00
|
|
|
{
|
2015-09-01 23:20:57 +02:00
|
|
|
return pool()->enqueue($task);
|
2015-08-28 07:18:50 +02:00
|
|
|
}
|
2015-09-02 15:51:59 +02:00
|
|
|
|
|
|
|
/**
|
2015-12-05 06:50:32 +01:00
|
|
|
* @param \Icicle\Concurrent\Worker\WorkerFactory|null $factory
|
2015-09-02 15:51:59 +02:00
|
|
|
*
|
2015-12-05 06:50:32 +01:00
|
|
|
* @return \Icicle\Concurrent\Worker\Worker
|
2015-09-02 15:51:59 +02:00
|
|
|
*/
|
2015-12-05 06:50:32 +01:00
|
|
|
function create(WorkerFactory $factory = null)
|
2015-09-02 15:51:59 +02:00
|
|
|
{
|
|
|
|
static $instance;
|
|
|
|
|
|
|
|
if (null !== $factory) {
|
|
|
|
$instance = $factory;
|
|
|
|
} elseif (null === $instance) {
|
2015-12-05 06:50:32 +01:00
|
|
|
$instance = new DefaultWorkerFactory();
|
2015-09-02 15:51:59 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
$worker = $instance->create();
|
|
|
|
$worker->start();
|
|
|
|
return $worker;
|
|
|
|
}
|
2015-08-28 07:18:50 +02:00
|
|
|
}
|