我還是比較新的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);
}
}
}
是的,我仍然在努力..你可以添加一些代碼:) – Baba 2013-05-19 17:52:34