symplely / thread_queue
一个简单的 `uv_queue_work` 包装API,用于管理线程池,以实现PHP的并行执行
dev-main
2023-03-19 15:21 UTC
This package is auto-updated.
Last update: 2024-09-19 18:47:26 UTC
README
一个简单的 uv_queue_work
包装API,用于 管理 一个 线程池,以实现 PHP 的并行 执行。
目录
此包使用 libuv
的功能,这是Node.js库的PHP扩展 ext-uv。它使用 `uv_queue_work` 函数创建线程。
安装
composer require symplely/thread_queue
此包将需要 libuv 功能,执行以下操作之一进行安装。
对于类似 Debian 的发行版,Ubuntu...
apt-get install libuv1-dev php-pear -y
对于类似 RedHat 的发行版,CentOS...
yum install libuv-devel php-pear -y
现在有 Pecl 自动编译、安装和设置。
pecl channel-update pecl.php.net pecl install uv-beta
对于 Windows,可以从PECL 获取稳定版本的PHP。
直接从 https://windows.php.net/downloads/pecl/releases/uv/ 下载最新版本
将 libuv.dll
解压到与 PHP
二进制可执行文件相同的目录,并将 php_uv.dll
解压到 ext\
目录。
在 php.ini 中启用扩展 php_uv.dll
cd C:\Php Invoke-WebRequest "https://windows.php.net/downloads/pecl/releases/uv/0.2.4/php_uv-0.2.4-7.2-ts-vc15-x64.zip" -OutFile "php_uv-0.2.4.zip" #Invoke-WebRequest "https://windows.php.net/downloads/pecl/releases/uv/0.2.4/php_uv-0.2.4-7.4-ts-vc15-x64.zip" -OutFile "php_uv-0.2.4.zip" 7z x -y php_uv-0.2.4.zip libuv.dll php_uv.dll copy php_uv.dll ext\php_uv.dll del php_uv.dll del php_uv-0.2.4.zip echo extension=uv >> php.ini
用法
include 'vendor/autoload.php'; use Async\Threads\Thread; $thread = new Thread(); $counter = 0; $t1 = $thread->create_ex(function () { print "Running Thread: 1\n"; return 2; })->then(function (int $output) use (&$counter) { $counter += $output; })->catch(function (\Throwable $e) { print $e->getMessage() . PHP_EOL; }); $t1->join(); // Or $t1->cancel(); print_r($t1->result()); // Or print_r($t1->exception());
事件钩子
当创建线程进程时,您将返回一个 TWorker
实例。您可以在一个 Thread
实例上添加以下事件 回调 钩子。
$thread = new Thread($function, ...$args) $worker = $thread->create($thread_id /* string or int */, function () { }, ...$arguments) ->then(function ($result) { // On success, `$result` is returned by the thread. }) ->catch(function ($exception) { // When an exception is thrown from within a thread, it's caught and passed here. }); $worker = $thread->create_ex(function () { }, ...$arguments) ->then(function ($result) { // On success, `$result` is returned by the thread. }) ->catch(function ($exception) { // When an exception is thrown from within a thread, it's caught and passed here. });
贡献
鼓励并欢迎贡献;我在Github上始终乐于获得反馈或拉取请求 :) 创建 Github问题 以报告错误和添加新功能,并对您感兴趣的问题进行评论。
许可
MIT许可证(MIT)。请参阅 许可文件 了解更多信息。