1
0
mirror of https://github.com/danog/parallel.git synced 2024-11-30 04:39:01 +01:00

Add some simple functions for global worker pool

This commit is contained in:
coderstephen 2015-08-28 00:18:50 -05:00
parent 6e317abe1b
commit 56b9360e0d
3 changed files with 49 additions and 8 deletions

View File

@ -35,7 +35,10 @@
"autoload": {
"psr-4": {
"Icicle\\Concurrent\\": "src"
}
},
"files": [
"src/Worker/functions.php"
]
},
"autoload-dev": {
"psr-4": {

View File

@ -2,23 +2,21 @@
<?php
require dirname(__DIR__).'/vendor/autoload.php';
use Icicle\Concurrent\Worker;
use Icicle\Concurrent\Worker\HelloTask;
use Icicle\Concurrent\Worker\WorkerPool;
use Icicle\Coroutine;
use Icicle\Loop;
use Icicle\Promise;
Coroutine\create(function () {
$pool = new WorkerPool(1);
$returnValues = (yield Promise\all([
new Coroutine\Coroutine($pool->enqueue(new HelloTask())),
new Coroutine\Coroutine($pool->enqueue(new HelloTask())),
new Coroutine\Coroutine($pool->enqueue(new HelloTask())),
new Coroutine\Coroutine(Worker\enqueue(new HelloTask())),
new Coroutine\Coroutine(Worker\enqueue(new HelloTask())),
new Coroutine\Coroutine(Worker\enqueue(new HelloTask())),
]));
var_dump($returnValues);
yield $pool->shutdown();
yield Worker\pool()->shutdown();
})->done();
Loop\run();

40
src/Worker/functions.php Normal file
View File

@ -0,0 +1,40 @@
<?php
namespace Icicle\Concurrent\Worker;
if (!function_exists(__NAMESPACE__ . '\pool')) {
/**
* Returns the default worker pool for the current context.
*
* @param WorkerPool $pool The instance to use as the default worker pool.
*
* @return WorkerPool
*/
function pool(WorkerPool $pool = null)
{
static $instance;
if (null !== $pool) {
$instance = $pool;
} elseif (null === $instance) {
$instance = new WorkerPool(4, 16);
}
return $instance;
}
/**
* Enqueues a task to be executed by the worker pool.
*
* @coroutine
*
* @param TaskInterface $task The task to enqueue.
*
* @return \Generator
*
* @resolve mixed The return value of the task.
*/
function enqueue(TaskInterface $task)
{
return pool()->enqueue($task);
}
}