pulyavin/thread-pool

Imitation of threads in PHP

dev-master 2017-10-31 07:58 UTC

This package is not auto-updated.

Last update: 2024-05-30 02:42:09 UTC


README

This library help to simply write PHP-code working in parallel processes

Installation

  1. Install Composer:

    curl -sS https://getcomposer.org/installer | php
    
  2. Add the dependency:

    php composer.phar require pulyavin/thread-pool:dev-master
    

Usage

Runnable

use League\ThreadPool\Interfaces\RunnableInterface;

class WorkerRunnable extends RunnableInterface
{
    use \League\ThreadPool\RunnableTrait;
    
    /**
     * @var LoggerInterface
     */
    private $logger;

    public function __construct(LoggerInterface $logger)
    {
        $this->logger = $logger;
    }

    /**
     * {@inheritdoc}
     */
    public function run()
    {
        try {
            while (true) {
                $this->logger->debug('We are working');
                $this->dispatchSignals();

                sleep(1);
            }
        }
        catch (InterruptedException $e) {
            $this->logger->debug('shutdown');

            return 0;
        }
        catch (\Exception $e) {
            return 1;
        }

        return 0;
    }
}

Thread

$runnable = new WorkerRunnable($logger);

$thread = new \League\ThreadPool\Thread($runnable);
$thread->setName("my awesome process");
$thread->registerShutdownFunction(function () {
    unset("/var/run/process.pid");
});

$thread->start();
$thread->wait();
$thread->read();

$exitCode = $thread->readExitCode();

ThreadPool

$threadPool = new \League\ThreadPool\ThreadPool;

for ($i = 0; $i < 5; $i++) {
    $runnable = new WorkerRunnable($logger);

    $thread = new \League\ThreadPool\Thread($runnable);
    $thread->setName("my awesome process #{$i}");
    
    $threadPool->submit($thread);
}

$threadPool->join(true);

Daemon

$runnable = new WorkerRunnable;
$thread = new \League\ThreadPool\Thread($runnable);
$thread->setName("my awesome process");

$daemon = new League\ThreadPool\Daemon($thread, "/path/to/pid/file");
$daemon->run();

Daemon as service

#!/usr/bin/env php
<?php

require_once("./vendor/autoload.php");

$runnable = new WorkerRunnable($logger);
$thread = new \League\ThreadPool\Thread($runnable);
$thread->setName("my awesome process");

$daemon = new \League\ThreadPool\Daemon($thread, "/path/to/pid/file");
$service = new \League\ThreadPool\Service\Service($daemon);

$service->run();