當前位置:首頁 » 編程語言 » php安裝pthreads

php安裝pthreads

發布時間: 2023-08-19 00:40:51

A. php的thread是個什麼情況

php通過擴展pthreads也可以支持線程上的操作,在mac下可以通過brew安裝pthreads擴展。線程類要繼承Thread類,而後實現run方法。

classcomputerextendsThread{

public$id;
public$runing=false;
public$params=null;

publicfunction__construct($id){
$this->id=$id;
$this->runing=true;
}

publicfunctionrun(){
while($this->runing){
if(is_null($this->params)){
echo"線程({$this->id})等待任務... ";
}else{
echo"線程({$this->id})收到任務參數::{$this->params}. ";
$this->params=null;
}
sleep(1);
}
}

}

不建議在PHP-FPM里使用多線程,寫不好會導致工作進程頻繁崩潰.使用PHP就應該轉變思路,不要照搬Java那一套.非同步處理耗時任務也不一定要使用多線程.你完全可以在PHP中用 pclose(popen('/path/to/task.php &', 'r')); 非同步打開一個進程處理耗時的任務,PHP-FPM則返回信息給瀏覽器提示"正在處理",task.php這個cli腳本處理完成任務後,把資料庫當前任務的狀態標記為"完成",前端AJAX定時輪詢到這個任務為"完成",則提示用戶即可.

B. PHP使用Pthread實現的多線程操作實例

本文實例講述了PHP使用Pthread實現的多線程操作。分享給大家供大家參考,具體如下:
<?php
class
vote
extends
Thread
{
public
$res
=
'';
public
$url
=
array();
public
$name
=
'';
public
$runing
=
false;
public
$lc
=
false;
public
function
__construct($name)
{
$this->res
=
'暫無,第一次運行.';
$this->param
=
0;
$this->lurl
=
0;
$this->name
=
$name;
$this->runing
=
true;
$this->lc
=
false;
}
public
function
run()
{
while
($this->runing)
{
if
($this->param
!=
0)
{
$nt
=
rand(1,
10);
echo
"線程[{$this->name}]收到任務參數::{$this->param},需要{$nt}秒處理數據.\n";
$this->res
=
rand(100,
999);
sleep($nt);
$this->lurl
=
$this->param;
$this->param
=
'';
}
else
{
echo
"線程[{$this->name}]等待任務..\n";
}
sleep(1);
}
}
}
//這里創建線程池.
$pool[]
=
new
vote('a');
$pool[]
=
new
vote('b');
$pool[]
=
new
vote('c');
//啟動所有線程,使其處於工作狀態
foreach
($pool
as
$w)
{
$w->start();
}
//派發任務給線程
for
($i
=
1;
$i
<
10;
$i++)
{
$worker_content
=
rand(10,
99);
while
(true)
{
foreach
($pool
as
$worker)
{
//參數為空則說明線程空閑
if
($worker->param=='')
{
$worker->param
=
$worker_content;
echo
"[{$worker->name}]線程空閑,放入參數{$worker_content},上次參數[{$worker->lurl}]結果[{$worker->res}].\n";
break
2;
}
}
sleep(1);
}
}
echo
"所有線程派發完畢,等待執行完成.\n";
//等待所有線程運行結束
while
(count($pool))
{
//遍歷檢查線程組運行結束
foreach
($pool
as
$key
=>
$threads)
{
if
($worker->param=='')
{
echo
"[{$threads->name}]線程空閑,上次參數[{$threads->lurl}]結果[{$threads->res}].\n";
echo
"[{$threads->name}]線程運行完成,退出.\n";
//設置結束標志
$threads->runing
=
false;
unset($pool[$key]);
}
}
echo
"等待中...\n";
sleep(1);
}
echo
"所有線程執行完畢.\n";
希望本文所述對大家php程序設計有所幫助。

熱點內容
蘋果耳塞怎麼改安卓也能用 發布:2025-02-05 14:50:54 瀏覽:557
安卓如何鑒別手機真假 發布:2025-02-05 14:28:15 瀏覽:119
ffmpeglinux編譯 發布:2025-02-05 14:28:04 瀏覽:544
伺服器如何做界面 發布:2025-02-05 14:27:23 瀏覽:290
訪問學者單位推薦意見 發布:2025-02-05 14:13:05 瀏覽:853
微信密碼鎖忘了怎麼辦 發布:2025-02-05 14:11:07 瀏覽:311
web是什麼文件夾 發布:2025-02-05 14:11:05 瀏覽:235
對信訪問題調查 發布:2025-02-05 14:09:39 瀏覽:984
singlephp 發布:2025-02-05 14:09:24 瀏覽:774
資料庫的欄位命名規則 發布:2025-02-05 13:53:16 瀏覽:684