PHP code example of sanmai / round-robin

1. Go to this page and download the library: Download sanmai/round-robin 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/ */

    

sanmai / round-robin example snippets


use RoundRobin\Scheduler;

$scheduler = new Scheduler();

$scheduler->add(new Fiber(function (): void {
    echo "task A: step 1\n";
    Fiber::suspend();
    echo "task A: step 2\n";
}));

$scheduler->add(new Fiber(function (): void {
    echo "task B: step 1\n";
    Fiber::suspend();
    echo "task B: step 2\n";
}));

$scheduler->run();

$queue = new SplQueue();
$done  = false;

$producer = new Fiber(function () use ($queue, &$done): void {
    foreach ([1, 2, 3] as $value) {
        $queue->enqueue($value);
        Fiber::suspend();
    }
    $done = true;
});

$consumer = new Fiber(function () use ($queue, &$done): void {
    while (!$done || !$queue->isEmpty()) {
        if ($queue->isEmpty()) {
            Fiber::suspend();
            continue;
        }

        echo "got {$queue->dequeue()}\n";
        Fiber::suspend();
    }
});

$scheduler->add($producer);
$scheduler->add($consumer);
$scheduler->run();