1

我对 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);
       }
    }
} 
4

1 回答 1

1

很难猜测 Image::* 方法的功能,所以我无法详细回答。

我能说的是,在任何情况下,我能想到的适合运行 20 个并发线程的机器很少。更合适的设置是工人/可堆叠模型。Worker 线程是一个可重用的上下文,可以一个接一个地执行任务,实现为 Stackables;在多线程环境中执行应始终使用最少的线程来完成尽可能多的工作。

请参阅与 pthreads 一起分发的池示例和其他示例,可在github上找到,此外,如果您在那之后仍然苦苦挣扎,那么过去的错误报告中包含了很多关于使用的信息......

于 2013-05-02T06:43:04.533 回答