我有一个使用PHP 7.0.22的pthreads v3.1.6的代码。我遇到的问题是线程不返回数组值。我的代码如下pthreads破坏数组结果
$threadCount = 1;
$url_idList = range(1,2000);
$url_idListChunked = array_chunk($url_idList, $threadCount);
class WorkerThreads extends Thread {
private $threadName, $url_id;
public function __construct($threadName,$url_id) {
$this->threadName = $threadName;
$this->url_id = $url_id;
$this->result = [];
}
public function run() {
if ($this->threadName && $this->url_id) {
printf('%sLoading URL #: %s' . "\n", $this->threadName, $this->url_id);
$this->result = send_request('GET',$this->url_id,NULL,$this->threadName);
}
}
}
while(count($url_idListChunked)){
$url_idListChunk = array_shift($url_idListChunked);
$workers = [];
foreach (range(0,count($url_idListChunk)-1) as $i) {
$threadName = "Thread #".$i.": ";
$workers[$i] = new WorkerThreads($threadName,$url_idListChunk[$i]);
$workers[$i]->start();
}
foreach (range(0,count($url_idListChunk)-1) as $i) {
$workers[$i]->join();
print_r($workers[$i]);
exit();
echo $workers[$i]['threadName']."Result for URL #: ".$workers[$i]['url_id']."\n";
}
}
function send_request($method,$url_id,$data,$threadName=NULL){
$url = 'https://www.example.tld/?id='.$url_id;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, TRUE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_TIMEOUT, 3);
if(!$data && $method=='POST'){
$data = generate_post_data();
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
}
$response = curl_exec($ch);
while((curl_errno($ch) == 6 OR curl_errno($ch) == 28)){
$response = curl_exec($ch);
echo $threadName.'Curl error #'.curl_errno($ch).' - ' . curl_error($ch)." Retrying.\n";
sleep(2);
}
curl_close($ch);
$result['data'] = $response;
return $result;
}
当我尝试print_t($workers)
我收到以下错误消息Uncaught RuntimeException: pthreads detected an attempt to connect to an object which has already been destroyed
。为什么我会失去数组结果?看起来线程没有问题将字符串传回。
首先,感谢您的回复。即使您提供了评论,我仍然无法理解代码。我尝试运行它,并行'$池 - >提交(新的WorkerThreads(($ i - 1),$ chunck));'是抛出和错误,说'Class'WorkerThreads'找不到'。另外,我还没有达到在$ list数组中有两个作业的目的。 –
您首先需要将pthreads dll添加到php.ini以使pthreads正常工作。它只能在cli模式下工作,因为你可能知道,所以你需要禁用DLL的xampp工作。 Vis等等......你可以添加任意数量的$ list_array,甚至可以为每个批次添加池的数量。这是一个简单的方法来跨批次同步wotk,并避免使用棘手的pthread syncro方法。 – tryHarder
pthreads.dll安装并正常工作。它找不到WorkerThreads类,而不是实际的Threaded类。 –