Запуск потоков с fork()


// Центальный поток ожидает завершения потомков

$pid = posix_getpid();
$THREADS = 2;
$pids = array();
echo "My pid: $pidn";
for($i=0;$i<$THREADS;$i++) {
    echo "cycle $in";
    $pid = pcntl_fork();
    if ($pid == -1) {
        die("Could not fork");
    } else if ($pid) {
        echo "Parent process #$pidn";
        $pids[]=$pid;
        sleep(rand(1,3));
    } else {
        echo "- Child process #$in";
        sleep(rand(1,3)+10);
        echo "- Child process #$i closedn";
        break;
    }
}
$pid = posix_getpid();
if (count($pids)==$THREADS) {
    echo "$pid Waits...n";
    $s=null; foreach($pids as $p) pcntl_waitpid($p,$s);
    echo "ALL DONE!n";
}