pthreads停止已经运行的线程,一旦条件得到满足
问题描述:
我还是比较新的PHP和尝试使用pthreads来解决问题。我有20个线程正在运行不同时间的进程。大部分在10秒左右完成<左右。我不需要全部20个,只有10个被发现。一旦我达到10,我想杀死线程,或者继续下一步。pthreads停止已经运行的线程,一旦条件得到满足
我已经尝试使用set_time_limit约20秒为每个线程,但他们忽略它,并继续运行。我正在循环寻找连接的工作,因为我不想让程序的其余部分运行,但我一直卡住,直到最慢的部分完成。虽然pthreads已经将时间从大约一分钟减少到大约30秒,但是我可以在大约3秒内从第一次10次运行以后花更多时间。
感谢您的帮助,这里是我的代码:
$count = 0;
foreach ($array as $i) {
$imgName = $this->smsId."_$count.jpg";
$name = "LocalCDN/".$imgName;
$stack[] = new AsyncImageModify($i['largePic'], $name);
$count++;
}
// Run the threads
foreach ($stack as $t) {
$t->start();
}
// Check if the threads have finished; push the coordinates into an array
foreach ($stack as $t) {
if($t->join()){
array_push($this->imgArray, $t->data);
}
}
class class AsyncImageModify extends \Thread{
public $data;
public function __construct($arg, $name, $container) {
$this->arg = $arg;
$this->name = $name;
}
public function run() {
//tried putting the set_time_limit() here, didn't work
if ($this->arg) {
// Get the image
$didWeGetTheImage = Image::getImage($this->arg, $this->name);
if($didWeGetTheImage){
$timestamp1 = microtime(true);
print_r("Starting face detection $this->arg" . "\n");
print_r(" ");
$j = Image::process1($this->name);
if($j){
// lets go ahead and do our image manipulation at this point
$userPic = Image::process2($this->name, $this->name, 200, 200, false, $this->name, $j);
if($userPic){
$this->data = $userPic;
print_r("Back from process2; the image returned is $userPic");
}
}
$endTime = microtime(true);
$td = $endTime-$timestamp1;
print_r("Finished face detection $this->arg in $td seconds" . "\n");
print_r($j);
}
}
}
答
这是很难猜测图片:: *方法的功能,所以在任何细节我真的不能回答。
我能说的是,我能想到的很少有机器适合在任何情况下运行20个并发线程。更合适的设置是工人/堆叠模型。 Worker线程是可重用的上下文,可以在任务后执行任务,实现为Stackables;在多线程环境中执行应该总是使用最少量的线程来完成尽可能多的工作。
Please see pooling example和分布与并行线程其他examples,在github可用,另外,对于使用多信息包含在过去的错误报告,如果你还在后挣扎......
是的,我仍然在努力..你可以添加一些代码:) – Baba 2013-05-19 17:52:34