PHP使用Pthread實(shí)現(xiàn)的多線程操作實(shí)例
更新時(shí)間:2015年11月14日 10:28:47 作者:jackluo
這篇文章主要介紹了PHP使用Pthread實(shí)現(xiàn)的多線程操作的方法,以完整實(shí)例形式分析了php多線程的創(chuàng)建及使用相關(guān)技巧,需要的朋友可以參考下
本文實(shí)例講述了PHP使用Pthread實(shí)現(xiàn)的多線程操作。分享給大家供大家參考,具體如下:
<?php
class vote extends Thread {
public $res = '';
public $url = array();
public $name = '';
public $runing = false;
public $lc = false;
public function __construct($name) {
$this->res = '暫無(wú),第一次運(yùn)行.';
$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}]收到任務(wù)參數(shù)::{$this->param},需要{$nt}秒處理數(shù)據(jù).\n";
$this->res = rand(100, 999);
sleep($nt);
$this->lurl = $this->param;
$this->param = '';
} else {
echo "線程[{$this->name}]等待任務(wù)..\n";
}
sleep(1);
}
}
}
//這里創(chuàng)建線程池.
$pool[] = new vote('a');
$pool[] = new vote('b');
$pool[] = new vote('c');
//啟動(dòng)所有線程,使其處于工作狀態(tài)
foreach ($pool as $w) {
$w->start();
}
//派發(fā)任務(wù)給線程
for ($i = 1; $i < 10; $i++) {
$worker_content = rand(10, 99);
while (true) {
foreach ($pool as $worker) {
//參數(shù)為空則說(shuō)明線程空閑
if ($worker->param=='') {
$worker->param = $worker_content;
echo "[{$worker->name}]線程空閑,放入?yún)?shù){$worker_content},上次參數(shù)[{$worker->lurl}]結(jié)果[{$worker->res}].\n";
break 2;
}
}
sleep(1);
}
}
echo "所有線程派發(fā)完畢,等待執(zhí)行完成.\n";
//等待所有線程運(yùn)行結(jié)束
while (count($pool)) {
//遍歷檢查線程組運(yùn)行結(jié)束
foreach ($pool as $key => $threads) {
if ($worker->param=='') {
echo "[{$threads->name}]線程空閑,上次參數(shù)[{$threads->lurl}]結(jié)果[{$threads->res}].\n";
echo "[{$threads->name}]線程運(yùn)行完成,退出.\n";
//設(shè)置結(jié)束標(biāo)志
$threads->runing = false;
unset($pool[$key]);
}
}
echo "等待中...\n";
sleep(1);
}
echo "所有線程執(zhí)行完畢.\n";
希望本文所述對(duì)大家php程序設(shè)計(jì)有所幫助。
相關(guān)文章
php提交post數(shù)組參數(shù)實(shí)例分析
這篇文章主要介紹了php提交post數(shù)組參數(shù)的用法,結(jié)合實(shí)例分析了php使用post進(jìn)行參數(shù)提交的相關(guān)技巧,需要的朋友可以參考下2015-12-12
PHP使用自定義key實(shí)現(xiàn)對(duì)數(shù)據(jù)加密解密的方法
這篇文章主要介紹了PHP使用自定義key實(shí)現(xiàn)對(duì)數(shù)據(jù)加密解密的方法,涉及php針對(duì)字符串的轉(zhuǎn)換、截取等操作實(shí)現(xiàn)加密解密功能的相關(guān)技巧,需要的朋友可以參考下2017-12-12
PHP對(duì)京東聯(lián)盟CPS的API調(diào)用
這篇文章介紹了PHP調(diào)用京東聯(lián)盟API的方法,文中通過(guò)示例代碼介紹的非常詳細(xì)。對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2022-07-07
php上傳文件并存儲(chǔ)到mysql數(shù)據(jù)庫(kù)的方法
這篇文章主要介紹了php上傳文件并存儲(chǔ)到mysql數(shù)據(jù)庫(kù)的方法,以完整實(shí)例形式較為詳細(xì)的分析了php操作文件上傳與數(shù)據(jù)庫(kù)存儲(chǔ)的技巧,具有一定參考借鑒價(jià)值,需要的朋友可以參考下2015-03-03
如何給phpcms v9增加類似于phpcms 2008中的關(guān)鍵詞表
本篇文章是對(duì)給phpcms v9增加類似于phpcms 2008中的關(guān)鍵詞表的方法進(jìn)行了詳細(xì)的分析介紹,需要的朋友參考下2013-07-07

