PHP code example of proilyxa / lara-thread

1. Go to this page and download the library: Download proilyxa/lara-thread library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

proilyxa / lara-thread example snippets


public static function run(string $class, mixed ...$params): Thread
 

use Swoole\Thread\Queue;

$start = microtime(true);

$input = new Queue();
$output = new Queue();

$d = 20;
for ($i = 0; $i < $d; $i++) {
    $input->push('https://dog.ceo/api/breeds/image/random');
}

// create workers
$t = 5;
$threads = [];
for ($threadID = 0; $threadID < $t; $threadID++) {
    $threads[] = LaraThread::run(Run::class, $threadID + 1, $input, $output);
}

$result = [];
for ($i = 0; $i < $d; $i++) {
    $result[] = $output->pop(-1);
}

dump(LaraThread::recursiveUnserialize($result));

// waiting for threads to finish
for ($i = 0; $i < count($threads); $i++) {
    $threads[$i]->join();
}

echo 'timeline: ' . round(microtime(true) - $start, 4) . ' s.';



declare(strict_types=1);

namespace App\Console\Commands;

use Illuminate\Support\Facades\Http;
use Swoole\Thread\ArrayList;
use Swoole\Thread\Map;
use Swoole\Thread\Queue;

class Run
{
    public function run(int $id, Queue $input, Queue $output): void
    {
        while (1) {
            $site = $input->pop();
            if ($site === null) {
                echo 'Thread: ' . $id . ' finished' . PHP_EOL;
                break;
            }
            $output->push(Http::get($site)->json(), Queue::NOTIFY_ONE);
            echo 'Thread: ' . $id . '  result pushed' . PHP_EOL;
        }
    }
}

bash
php artisan vendor:publish --tag=proilyxa-lara-thread