热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

php多线程怎么实现(一览php多线程实现方法)

1、curl_multi方法当需要多线程的时候,可以用curl_multi一次性请求多个操作来完成,但curl走的是网络通信,效率与可靠性就比较差了的。functionmain()

1、curl_multi方法

当需要多线程的时候,可以用curl_multi一次性请求多个操作来完成,但curl走的是网络通信,效率与可靠性就比较差了的。

function main(){

$sql = "select waybill_id,order_id from waybill where status>40 order by update_time desc limit 10 ";

$data = yii::app()->db->createcommand($sql)->queryall(); //yii 框架格式

foreach ($data as $k => $v) {

if ($k % 2 == 0) { //偶数发一个网址

$send_data[$k]['url'] = '';

$send_data[$k]['body'] = $v['waybill_id'];

} else { //奇数发送另外一个网址
$send_data[$k]['url'] = 'http://www.abc.com';

$send_data[$k]['body']=array($v['order_id'] => array('extra' => 16));
}
}
}

2、通过stream_socket_client 方式

function sendstream() {
$english_format_number = number_format($number, 4, '.', '');

echo $english_format_number;
exit();
$timeout = 10;
$result = array();
$sockets = array();
$convenient_read_block = 8192;
$host = "test.local.com";
$sql = "select waybill_id,order_id from xm_waybill where status>40 order by update_time desc limit 1 ";
$data = yii::app()->db->createcommand($sql)->queryall();
$id = 0;

foreach ($data as $k => $v) {
if ($k % 2 == 0) {
$send_data[$k]['body'] = noticeorder::getsenddata($v['waybill_id']);

} else {
$send_data[$k]['body'] = array($v['order_id'] => array('extra' => 16));
}
$data = json_encode($send_data[$k]['body']);
$s = stream_socket_client($host . ":80", $errno, $errstr, $timeout, stream_client_async_connect | stream_client_connect);
if ($s) {
$sockets[$id++] = $s;
$http_message = "get /php/test.php?data=" . $data . " http/1.0\r\nhost:" . $host . "\r\n\r\n";
fwrite($s, $http_message);
} else {
echo "stream " . $id . " failed to open correctly.";
}
}
}

3、通过多进程代替多线程

function daemon($func_name,$args,$number){

while(true){

$pid=pcntl_fork();

if($pid==-1){

echo “fork process fail”;

exit();

}elseif($pid){//创建的子进程

static $num=0;

$num++;

if($num>=$number){

//当进程数量达到一定数量时候,就对子进程进行回收。

pcntl_wait($status);

$num–;

}

}else{ //为0 则代表是子进程创建的,则直接进入工作状态

if(function_exists($func_name)){

while (true) {

$ppid=posix_getpid();

var_dump($ppid);

call_user_func_array($func_name,$args);

sleep(2);

}

}else{

echo “function is not exists”;

}

exit();

}

}

}

function worker($args){

//do something

}

daemon(‘worker’,array(1),2);



推荐阅读
author-avatar
闹闹依旧不闹
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有