2013-05-01 87 views
1

我還是比較新的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); 
     } 
    } 
} 

回答

1

這是很難猜測圖片:: *方法的功能,所以在任何細節我真的不能回答。

我能說的是,我能想到的很少有機器適合在任何情況下運行20個併發線程。更合適的設置是工人/堆疊模型。 Worker線程是可重用的上下文,可以在任務後執行任務,實現爲Stackables;在多線程環境中執行應該總是使用最少量的線程來完成儘可能多的工作。

Please see pooling example和分佈與並行線程其他examples,在github可用,另外,對於使用多信息包含在過去的錯誤報告,如果你還在後掙扎......

+0

是的,我仍然在努力..你可以添加一些代碼:) – Baba 2013-05-19 17:52:34

相關問題