zerustech/threaded

ZerusTech 线程组件

dev-master / 2.2.x-dev 2016-08-31 12:27 UTC

This package is auto-updated.

Last update: 2024-09-09 15:31:31 UTC


README

Build Status

ZerusTech 线程组件

ZerusTech 线程组件 是一个库,提供了一些常用的线程安全类,例如管道输入流和管道输出流。

感谢 krakjoe/pthreads 扩展,最终可以在 php-cli 中开发多线程应用程序。

::: info-box note

这是 2.x 版本,适用于 PHP 7.x 和 pthreads 3.x。

如果您想使用 pthreads 2.x,请安装 1.x 版本。

:::

安装

您可以通过两种方式安装此组件

  • 通过 Composer 安装

    $ cd <project-root-directory>
    $ composer require zerustech/threaded:2.*
    
  • 使用官方 Git 仓库 zerustech/threaded

示例

管道流

管道输入流将其自身与管道输出流(上游)连接起来,并从上游读取数据,而管道输出流将其自身连接到管道输入流(下游),并向下游写入数据。

它们都是线程安全类,因此可以用于构建多线程应用程序。

当上游为空时,管道输入流将被阻塞,如果下游已满,管道输出流也将被阻塞。

阻塞的管道输入流将在管道输出流写入数据或关闭时被通知,而阻塞的管道输出流将在管道输入流从上游读取数据或关闭时被通知。

<?php

require_once __DIR__.'/vendor/autoload.php';

use ZerusTech\Component\Threaded\Stream\Input\PipedInputStream;
use ZerusTech\Component\Threaded\Stream\Output\PipedOutputStream;

/**
 * The consumer class that reads data from a piped input stream.
 *
 * @author Michael Lee <michae.lee@zerustech.com>
 */
class Consumer extends \Thread
{
    /**
     * @var PipedInputStream $input The piped input stream.
     */
    private $input;

    /**
     * @var int $lenght The number of bytes to be read. 
     */
    private $length;

    /**
     * Constructor.
     *
     * @param PipedInputStream $input The piped input stream.
     * @param int $length The number of bytes to be read.
     */
    public function __construct(PipedInputStream $input, $length)
    {
        $this->input = $input;

        $this->length = $length;
    }

    /**
     * {@inheritdoc}
     */
    public function run()
    {
        $remaining = $this->length;

        while (0 < $remaining--) {

            // If the piped input stream is empty, the thread will be blocked.
            $data = $this->input->read();

            printf("%s", $data);
        }
    }
}

// Initializes a piped output stream.
$output = new PipedOutputStream();

// Initializes a piped input stream.
$input = new PipedInputStream();

// Connects the piped output stream with the piped input stream.
$input->connect($output);

// Initializes a consumer.
$consumer = new Consumer($input, 5);

// Starts the consumer thread.
// It will try to read up to 5 bytes from the piped input stream.
$consumer->start();

for ($i = 0; $i < 5; $i++) {

    // Writes one byte per time to the piped output stream
    // The blocked consumer thread will be notified as soon as the byte is 
    // written to the piped output stream.
    $output->write('*');

    sleep(1);
}

// Waits till the consumer thread ends.
$consumer->join();

参考

许可证

ZerusTech 线程组件 根据 MIT 许可证 发布。