首页 > 解决方案 > 使用 pcntl_fork 后如何从主线程打印

问题描述

我已经举了这个例子(你可以从那个链接下载 Thread.php 以及我在这里玩的原始测试代码):

https://stackoverflow.com/a/9014136/1678312

我想做的事:

  1. 等到我创建的所有子进程都完成
  2. 从主线程打印到浏览器,所有子线程都已完成。

问题是 - 一旦我分叉,我就失去了在页面上打印任何内容的能力(请参阅下面示例中的最后一行)

在我的示例中,如何从主线程打印?

我正在使用的片段如下:

<?php
require_once( 'Thread.php' );

// test to see if threading is available
if( ! Thread::isAvailable() ) {
    die( 'Threads not supported' );
}

// function to be ran on separate threads
function parallel( $_limit, $_name ) {
    for ( $index = 0; $index < $_limit; $index++ ) {
        echo 'Now running thread ' . $_name . PHP_EOL;
        sleep( 1 );
    }

    var_dump("child is running=".$_name);
}

// create 2 thread objects
$t1 = new Thread( 'parallel' );
$t2 = new Thread( 'parallel' );

// start them
$t1->start( 10, 't1' );
$t2->start( 10, 't2' );

// keep the program running until the threads finish
while( $t1->isAlive() && $t2->isAlive() ) {

}

var_dump('main thread has reached last execution line');
?>

标签: phpmultithreadingparallel-processingpcntl

解决方案


推荐阅读