简体   繁体   English

从php线程获取返回值

[英]Get return value from php threads

This is the sample code, I'm working on 这是示例代码,我正在研究

class workerThread extends Thread {
  public function __construct($i){
     $this->i=$i;
}

public function run(){
  while(true){
   echo $this->i;
   sleep(1);
  }
}
}

for($i=0;$i<50;$i++){
$workers[$i]=new workerThread($i);
$workers[$i]->start();
}

What is the appropriate way to get return value from run() or should create another function for callback? 从run()获取返回值的适当方法是什么,还是应该为回调创建另一个函数?

well first you have to wait for all threads to finish. 首先,您必须等待所有线程完成。

so after your initial loop you should do one more loop waiting for each worker to finish. 因此,在您的初始循环之后,您应该再执行一次循环以等待每个工作人员完成。 there is thread->join function that syncs your main thread with the sub-thread. thread->join函数可以将您的主线程与子线程同步。 causing to halt the execution and wait until the sub thread finishes. 导致执行停止并等待子线程完成。 so if you call if($worker->join()) {...} you can be sure, that the worker is done working :) 因此,如果您调用if($worker->join()) {...} ,则可以确定该工作器已完成工作:)

http://php.net/manual/de/thread.join.php http://php.net/manual/de/thread.join.php

second, a thread does not return a value. 第二,线程不返回值。 instead create a variable in your class, for example result and fill it with data during the run of a thread. 而是在类中创建一个变量,例如result并在线程运行期间将其填充数据。 collect at the end (after join ) the $worker->result 最后( join后)收集$worker->result

third, your current threads even cannot report any result, as they run for ever. 第三,您当前的线程甚至无法报告任何结果,因为它们永远运行。 From the question I dont understand, if you want them to run for ever? 从我不明白的问题来看,是否要让它们永远运行? Because if you do there are more complicated steps involved to get the results continuously. 因为如果这样做,将涉及更复杂的步骤来连续获得结果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM