alicemajere/wonderland-thread

简单的多线程管理库

1.0.0 2018-10-20 16:47 UTC

This package is auto-updated.

Last update: 2024-09-05 06:09:09 UTC


README

Build Status Scrutinizer Code Quality Code Coverage Code Intelligence Status License

Wonderland Thread

一个小巧简单的多线程库,可用于项目

最近更新

该项目刚刚在 Packagist 上发布,版本号为 1.0.0。

安装

您需要安装 composer 和 autloader。为了安装此包,请在您的 composer.json 的 "repositories" 指索引中添加此条目

      {
        "type": "vcs",
        "url":  "git@github.com:AliceMajere/wonderland-thread.git"
      }

只需使用 composer 要求包

composer require alicemajere/wonderland-thread

用法

要启动一个多线程池,只需创建 ThreadPool 的新实例

$threadPool = new ThreadPool(); 

我们设置同时运行的线程的最大数量。如果我们向池中添加 200 个线程,只有 5 个线程会同时运行,直到池处理完所有 200 个线程

$threadPool->setMaxRunningThreadNb(5);

通过创建 Thread 的新实例向池中添加一个或多个线程。线程需要两个参数,一个名称和一个闭包函数,该函数将告诉线程该做什么。闭包必须从 Thread 类的常量中返回一个退出状态。

$thread = ThreadFactory::create(
    'ThreadName',
    function ($processName) {
        // Implements the Thread processing here
        echo $processName . PHP_EOL;
        
        // return an exit status at the end of the thread
        return Thread::EXIT_STATUS_SUCCESS;
    }
)

$threadPool->addThread($thread);

要运行 ThreadPool,您可以这样做

$threadPool->run();

您可以在池运行线程时添加监听器,以便在特定事件触发。使用监听器可以非常有用,如果您需要为每个线程执行特定操作,例如为每个线程打开一个单独的 mysql 连接。监听器对象构造函数需要监听的事件名称和闭包函数,该函数将告诉监听器针对此事件该做什么。事件定义的完整列表可以在 Event 类中找到。

$threadPool->addListener(new Listener(
    Event::POOL_RUN_START, // Event to trigger the listener
    function (Event $event) use ($website) {
        // Implements the listener
    })
);
$threadPool->addListener(new Listener(
    Event::POOL_RUN_STOP,
    function (Event $event) {
        $this->io->progressFinish();
    })
);

先决条件

PHP >= 7.2

获取帮助

如果您在库中发现了错误或希望添加新功能,请打开此存储库的问题或拉取请求!

作者