Created
April 9, 2018 16:42
-
-
Save maxwellimpact/1c53320e77c5ef0737c7068b69cbeb2d to your computer and use it in GitHub Desktop.
A simple scratch script for testing parallel processes in PHP.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
use Symfony\Component\Console\Output\ConsoleOutput; | |
use Symfony\Component\Process\Process; | |
require_once __DIR__ . '/../../vendor/autoload.php'; | |
/* | |
* Playing with using only Process to handle parallel processes | |
* but still enabling each to stream their content at the same time. | |
* Uses proc_open on under the hood and doesn't allow call backs. It | |
* does cut down on needing to fork a process first. | |
*/ | |
$output = new ConsoleOutput(); | |
/** @var Process $processes */ | |
$processes = []; | |
$processes[] = new Process('php /app/scripts/dummy.php 1'); | |
$processes[] = new Process('php /app/scripts/dummy.php 2'); | |
$processes[] = new Process('php /app/scripts/dummy.php 3'); | |
/** @var Process $process */ | |
foreach ($processes as $process) { | |
$process->start(); | |
} | |
// Output the data | |
foreach (streamProccessesOutput($processes) as $type => $data) { | |
echo $data; | |
} | |
foreach ($processes as $process) { | |
$process->wait(); | |
} | |
// TODO: make this more performant | |
function streamProccessesOutput($processes) | |
{ | |
while (count($processes)) { | |
/** @var Process $process */ | |
foreach ($processes as $key => $process) { | |
$value = $process->getIterator()->current(); | |
if ($value) { | |
yield $value; | |
} elseif (!$process->isRunning()) { | |
unset($processes[$key]); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment