PHP code example of polonskiy / phproutine

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

    

polonskiy / phproutine example snippets




e __DIR__ . '/../src/Runner.php';

use PHProutine\Channel;
use PHProutine\Runner;

// intDoubler doubles the given int, then sends it through the given channel
function intDoubler($ch, $n) {
    $ch->write($n * 2);
}

$runner = new Runner;
// Make channels
$ch = new Channel;
$answer = new Channel;

// Spawn 3 PHProutines (basically PROCESSES) to process data in background
$runner->go('intDoubler', $ch, 10);
$runner->go('intDoubler', $ch, 20);
$runner->go(function($a, $b) use ($ch) { $ch->write($a + $b); }, 30, 40);

// Create anonymous function on the fly, launch as PHProutine!
$runner->go(function() use ($ch, $answer) {
    // Save the 3 values passed through the channel as x, y, and z
    list($x, $y, $z) = [$ch->read(), $ch->read(), $ch->read()];
    // Calculate answer, write to `answer` channel
    $answer->write(sprintf('%d + %d + %d = %d', $x, $y, $z, $x + $y + $z));
});

// Print answer resulting from channel read
printf("%s\n", $answer->read());



HProutine\Runner;

$server = stream_socket_server('tcp://127.0.0.1:8000');
$runner = new Runner;
while (true) {
    $client = stream_socket_accept($server, -1);
    $runner->go(function() use ($client) {
        stream_copy_to_stream($client, $client);
    });
    fclose($client);
}



//usage: php sleepsort.php 3 2 1 4

se PHProutine\Channel;
use PHProutine\Runner;

$runner = new Runner;
$channel = new Channel;

array_shift($argv);
foreach ($argv as $val) {
    $runner->go(function($v) use ($channel) {
        sleep($v);
        $channel->write($v);
    }, $val);
}

foreach ($argv as $val) {
    echo $channel->read(), "\n";
}