php - 使用 pcntl_fork 后如何从主线程打印
问题描述
我已经举了这个例子(你可以从那个链接下载 Thread.php 以及我在这里玩的原始测试代码):
https://stackoverflow.com/a/9014136/1678312
我想做的事:
- 等到我创建的所有子进程都完成
- 从主线程打印到浏览器,所有子线程都已完成。
问题是 - 一旦我分叉,我就失去了在页面上打印任何内容的能力(请参阅下面示例中的最后一行)
在我的示例中,如何从主线程打印?
我正在使用的片段如下:
<?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');
?>
解决方案
推荐阅读
- swift - 将 .usdz 加载到自定义实体类中时出现问题
- ios - 如何在 UITableViewCell 中获得正确的 UIView 宽度?
- javascript - 使用 require 导入文件时电子/节点脚本中断
- haskell - 解释泛型类型不一致
- ruby-on-rails - 我可以检查是否从 Rails 中的 AMP 页面调用控制器?
- javascript - 如何并行运行两个 node.js 项目?
- python - Rundeck - 我为运行 python 脚本而创建的作业调用了不同的 python
- python-3.x - 如何编写一个接受字符串的函数,将其编码为数字并在 Python 中将数字作为字符串返回?
- java - 如何在 Android 中制作共享库?
- javascript - 使用带有鳗鱼的Python函数的Javascript