Parallel
Parallel là một công cụ lập lịch tác vụ song song, cho phép thực hiện nhiều tác vụ bất đồng bộ đồng thời trong chương trình và nhận kết quả khi tất cả các tác vụ đã hoàn thành. Parallel được xây dựng trên cơ sở Barrier.
Lưu ý
Tự động nhận diện loại trình điều khiển, chỉ hỗ trợ Swoole/Swow/FiberMẹo
Tính năng này yêu cầu 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; // Hoặc Swow::class hoặc Fiber::class
$worker->onMessage = function (TcpConnection $connection, Request $request) {
$parallel = new Parallel();
for ($i=1; $i<5; $i++) {
$parallel->add(function () use ($i) {
// Thực hiện một cái gì đó
return $i;
});
}
$results = $parallel->wait();
$connection->send(json_encode($results)); // Phản hồi: [1,2,3,4]
};
Worker::runAll();
Ghi chú về giao diện
interface ParallelInterface
{
/**
* Hàm khởi tạo, $concurrent là số lượng tác vụ song song, -1 nghĩa là không giới hạn số lượng tác vụ song song
*/
public function __construct(int $concurrent = -1);
/**
* Thêm một tác vụ song song
*/
public function add(callable $callable, ?string $key = null): void;
/**
* Chờ tất cả các tác vụ hoàn thành và trả về kết quả
*/
public function wait(): array;
/**
* Lấy kết quả xảy ra ngoại lệ trong các tác vụ
*/
public function getExceptions(): array;
}