我对 PHP 还比较陌生,并尝试使用 pthreads 来解决问题。我有 20 个线程运行的进程在不同的时间结束。大多数完成大约<10秒左右。我不需要全部 20 个,只检测到 10 个。一旦我达到 10,我想杀死线程,或者继续下一步。
我已经尝试为每个线程使用 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);
}
}
}