Parallel
Parallel is a parallel task scheduling tool that allows multiple asynchronous tasks to be executed concurrently within a program, and retrieves the results once all tasks are completed. Parallel is based on Barrier.
Note
The underlying driver type is automatically recognized and only supports Swoole/Swow/Fiber drivers.Tip
This feature requires workerman >= 5.1.0
<?php
use Workerman\Connection\TcpConnection;
use Workerman\Coroutine\Parallel;
use Workerman\Events\Swoole;
use Workerman\Protocols\Http\Request;
use Workerman\Worker;
require_once __DIR__ . '/vendor/autoload.php';
// Http Server
$worker = new Worker('http://0.0.0.0:8001');
$worker->eventLoop = Swoole::class; // Or Swow::class or Fiber::class
$worker->onMessage = function (TcpConnection $connection, Request $request) {
$parallel = new Parallel();
for ($i=1; $i<5; $i++) {
$parallel->add(function () use ($i) {
// 执行某些操作
return $i;
});
}
$results = $parallel->wait();
$connection->send(json_encode($results)); // 响应: [1,2,3,4]
};
Worker::runAll();
Interface Description
interface ParallelInterface
{
/**
* Constructor, $concurrent is the number of concurrent tasks, -1 means no limit on the number of concurrent tasks
*/
public function __construct(int $concurrent = -1);
/**
* Add a parallel task
*/
public function add(callable $callable, ?string $key = null): void;
/**
* Wait for all tasks to complete and return results
*/
public function wait(): array;
/**
* Get the results of tasks that encountered exceptions
*/
public function getExceptions(): array;
}