PHP如何实现多进程,由于php的进程是不支持多线程的
分类:热门资源

鉴于php的进程是不帮助四十多线程的,有些场景为了便利以致压实品质,能够用php达成多进度以弥补这一个不足:
复制代码 代码如下:
#!/usr/bin/env php
$cmds=array(
        array('/apps/bin/launcher.php','charge/promotion_props_stat.php','mobile',1),
        array('/apps/bin/launcher.php','charge/promotion_props_stat.php','mobile',2),
        array('/apps/bin/launcher.php','charge/promotion_props_stat.php','click',1),
        array('/apps/bin/launcher.php','charge/promotion_props_stat.php','click',2),
        array('/apps/bin/launcher.php','charge/promotion_props_stat.php',1),
        array('/apps/bin/launcher.php','charge/promotion_props_stat.php',2)
);

PHP如何达成多进度?

注意:

foreach($cmds as $cmd){
        $pid=pcntl_fork();
        if($pid==-1State of Qatar{ //进度创设失利
                die('fork child process failure!');
        }
        else if($pid卡塔尔(قطر‎{ //父进度管理逻辑
                pcntl_wait($status,WNOHANG);
        }
        else{ //子进度管理逻辑
                pcntl_exec('/usr/local/bin/php',$cmd);
        }
}

PHP实现多进度并行试行脚本

PHP有个pcntl_fork的函数能够兑现多进度,但要加载pcntl拓展,並且唯有在linux下能力编译那一个进行

是因为php的进度是不协助四线程的,某个场景为了方便以及升高质量,能够用php完毕多进度以弥补那个不足:

1.率先在ubuntu下编写翻译pcntl.so,小编的ubuntu下找不到pcntl的包,于是

 

创办三个文件夹下载了全数PHP包,在里面找到了pcntl包运维如下命令

#!/usr/bin/env php

 代码如下

<?php

# mkdir php
# cd php
# apt-get source php5
# cd php5-(WHATEVER_RELEASE)/ext/pcntl
# phpize
# ./configure (注一)
# make
# make install phpize 命令是用来计划 PHP 外挂模块的编写翻译情况的。

$cmds=array(

水到渠成的安装将创建 extname.so 并放置于 PHP 的外挂模块目录中 (预设寄存于 /usr/lib/php/modules/ 内卡塔尔国 。
亟需调解 php.ini,插足 extension=extname.so 那风流浪漫行之后技巧应用其余挂模块。

array('/apps/bin/launcher.php','charge/promotion_props_stat.php','mobile',1),

array('/apps/bin/launcher.php','charge/promotion_props_stat.php','mobile',2),

void pcntl_exec ( string $path [, array $args [, array $envs ]] )

array('/apps/bin/launcher.php','charge/promotion_props_stat.php','click',1),

pcntl_exec — 在当前经过空间实践内定程序

array('/apps/bin/launcher.php','charge/promotion_props_stat.php','click',2),

 代码如下

array('/apps/bin/launcher.php','charge/promotion_props_stat.php',1),

$cmds=array(

array('/apps/bin/launcher.php','charge/promotion_props_stat.php',2)

        array('/home/jerry/projects/www/test2.php'),

);

        array('/home/jerry/projects/www/test3.php')

 

);

foreach($cmds as $cmd){

 

$pid=pcntl_fork();

foreach($cmds as $cmd){

if($pid==-1卡塔尔(قطر‎{ //进程创制退步

        $pid=pcntl_fork();

die('fork child process failure!');

        if($pid==-1){

}

        //进度创立败北

else if($pid卡塔尔(قطر‎{ //父进度管理逻辑

            echo '创制子进度受挫时回来-1';

pcntl_wait($status,WNOHANG);

            exit(-1);

}

        }

else{ //子进度管理逻辑

        else if($pid){

pcntl_exec('/usr/local/bin/php',$cmd);

        //父进程会收获子进度号,所以这里是父进程执行的逻辑

}

            pcntl_wait($status,WNOHANG);

}

        }

 

        else{

PHP 5.3 以上版本,使用pthreads PHP扩充,可以使PHP真正地支撑四线程。十六线程在管理重复性的循环职务,能够大大减弱程序推行时间。

        //子进度管理逻辑

   笔者前边的篇章中说过,大大多网址的性质瓶颈不在PHP服务器上,因为它能够归纳地经过横向扩充服务器或CPU核数来轻松答对(对于各类云主机,增加VPS或CPU核数就更低价了,直接以备份镜像扩充VPS,连操作系统、景况都不用安装配置),而是在于MySQL数据库。若是用 MySQL 数据库,一条联合查询的SQL,恐怕就足以管理完业务逻辑,但是,境遇多量并发央浼,就歇菜了。纵然用 NoSQL 数据库,大概必要11次询问,才具处理完同样地工作逻辑,但每趟查询都比 MySQL 要快,十一次循环NoSQL查询恐怕比叁遍MySQL联合查询更加快,应对几万次/秒的查询完全没难点。若是加上PHP八线程,通过12个线程同有的时候候查询 NoSQL,再次来到结果汇总输出,速度将在越来越快了。大家其实的应用软件付加物中,调用三个经过客户喜好实时推荐商品的PHP接口,PHP要求对BigSea NoSQL数据库发起500~1000次询问,来实时算出客商的秉性喜好商品数量,PHP四线程的效益特别醒目。

            sleep(5);

  PHP增添下载:
  PHP手册文书档案:

            pcntl_exec('/usr/bin/php',$cmd);

  1、扩展的编写翻译安装(Linux),编辑参数 --enable-maintainer-zts 是必选项:

            exit(0);

cd /Data/tgz/php-5.5.1
./configure --prefix=/Data/apps/php --with-config-file-path=/Data/apps/php/etc --with-mysql=/Data/apps/mysql --with-mysqli=/Data/apps/mysql/bin/mysql_config --with-iconv-dir --with-freetype-dir=/Data/apps/libs --with-jpeg-dir=/Data/apps/libs --with-png-dir=/Data/apps/libs --with-zlib --with-libxml-dir=/usr --enable-xml --disable-rpath --enable-bcmath --enable-shmop --enable-sysvsem --enable-inline-optimization --with-curl --enable-mbregex --enable-fpm --enable-mbstring --with-mcrypt=/Data/apps/libs --with-gd --enable-gd-native-ttf --with-openssl --with-mhash --enable-pcntl --enable-sockets --with-xmlrpc --enable-zip --enable-soap --enable-opcache --with-pdo-mysql --enable-maintainer-zts
make clean
make
make install        

        }

unzip pthreads-master.zip
cd pthreads-master
/Data/apps/php/bin/phpize
./configure --with-php-config=/Data/apps/php/bin/php-config
make
make install

}

 

 

vi /Data/apps/php/etc/php.ini

例,

 

实例多图片同步下载

添加:

 代码如下

extension = "pthreads.so"

#!/usr/bin/php
<?php
// 须求抓取的网页地址
$url = '';
$content = file_get_contents($url);
preg_match_all('/<imgs+src="(.*?)"/', $content, $matches,PREG_SET_ORDER);
echo "已发现".count($matches)."张图片n";
 
list($sm, $ss) = explode(" ", microtime());
foreach ($matches as $k => $val)
{
 $pid[$k] = pcntl_fork();
 if(!$pid[$k])
 {
  download($url, $val);
  // 子进程要exit不然博览会开递归多进度,父进度不要exit不然甘休多进程
  exit(0);
 }
 
 if ($pid[$k])
 {
//    pcntl_waitpid($pid[$k], $status, WUNTRACED);
 }
 
}
echo "下载达成n";
 
list($em, $es) = explode(" ", microtime());
 
echo "用时:",($es+$em) - ($ss + $sm),"n";
/**
 * 抓取网页图片
 *
 */
function download($url, $val)
{
 $pic_url = $val[1];
 if (strpos($val[1], '//') !== false)
 {
  ;
 }
 elseif (preg_match('@^(.*?)/@', $val[1], $inner_matches) == 0)
 {
  $pic_url = $url.$val[1];
 }
 elseif (preg_match('@[:.]@', $inner_matches[1], $tmp_matches) == 0)
 {
  $pic_url = $url.$val[1];
 }
 
 $pic = file_get_contents($pic_url);
 
 if ($pic === false)
 {
  return;
 }
 
 preg_match('@/([^/]+)$@', $pic_url, $tmp_matches);
 // 可选用assert管理极其
 $pic_file_name = $tmp_matches[1];
 $f = fopen("tmp/".$pic_file_name, "wb"); #
 fwrite($f, $pic);
 fclose($f);
}
 
/* End of file pcntl_fork.php */

 2、给出一段PHP多线程、与For循环,抓取百度寻觅页面包车型大巴PHP代码示例:

文件1

<?php

class test_thread_run extends Thread

{

public $url;

public $data;

 

public function __construct($url)

{

$this->url = $url;

}

 

public function run()

{

if(($url = $this->url))

{

$this->data = model_http_curl_get($url);

}

}

}

 

function model_thread_result_get($urls_array)

{

foreach ($urls_array as $key => $value)

{

$thread_array[$key] = new test_thread_run($value["url"]);

$thread_array[$key]->start();

}

 

foreach ($thread_array as $thread_array_key => $thread_array_value)

{

while($thread_array[$thread_array_key]->isRunning())

{

usleep(10);

}

if($thread_array[$thread_array_key]->join())

{

$variable_data[$thread_array_key] = $thread_array[$thread_array_key]->data;

}

}

return $variable_data;

}

 

function model_http_curl_get($url,$userAgent="")

{

$userAgent = $userAgent ? $userAgent : 'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.2)';

$curl = curl_init();

curl_setopt($curl, CURLOPT_URL, $url);

curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);

curl_setopt($curl, CURLOPT_TIMEOUT, 5);

curl_setopt($curl, CURLOPT_USERAGENT, $userAgent);

$result = curl_exec($curl);

curl_close($curl);

return $result;

}

 

for ($i=0; $i < 100; $i++)

{

$urls_array[] = array("name" => "baidu", "url" => "));

}

 

$t = microtime(true);

$result = model_thread_result_get($urls_array);

$e = microtime(true);

echo "多线程:".($e-$t)."n";

 

$t = microtime(true);

foreach ($urls_array as $key => $value)

{

$result_new[$key] = model_http_curl_get($value["url"]);

}

$e = microtime(true);

echo "For循环:".($e-$t)."n";

?>

 

文件2

<?php

class

test_thread_run extends Thread

{

public $url;

public $data;

 

public function __construct($url)

{

$this->url

= $url;

}

 

public function run()

{

if(($url =

$this->url))

{

$this->data

= model_http_curl_get($url);

}

}

}

 

function model_thread_result_get($urls_array)

{

foreach ($urls_array as $key =>

$value)

{

$thread_array[$key]

= new test_thread_run($value["url"]);

$thread_array[$key]->start();

}

 

foreach

($thread_array as $thread_array_key => $thread_array_value)

{

while($thread_array[$thread_array_key]->isRunning())

{

usleep(10);

}

if($thread_array[$thread_array_key]->join())

{

$variable_data[$thread_array_key]

= $thread_array[$thread_array_key]->data;

}

}

return $variable_data;

}

 

function model_http_curl_get($url,$userAgent="")

{

$userAgent = $userAgent ? $userAgent

: 'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.2)';

$curl = curl_init();

curl_setopt($curl, CURLOPT_URL,

$url);

curl_setopt($curl,

CURLOPT_RETURNTRANSFER, 1);

curl_setopt($curl, CURLOPT_TIMEOUT,

5);

curl_setopt($curl,

CURLOPT_USERAGENT, $userAgent);

$result = curl_exec($curl);

curl_close($curl);

return $result;

}

 

for ($i=0; $i < 100; $i++)

{

$urls_array[] = array("name" =>

"baidu", "url" => "));

}

 

$t = microtime(true);

$result = model_thread_result_get($urls_array);

$e = microtime(true);

echo "多线程:".($e-$t)."n";

 

$t = microtime(true);

foreach ($urls_array as $key => $value)

{

$result_new[$key] =

model_http_curl_get($value["url"]);

}

$e = microtime(true);

echo "For循环:".($e-$t)."n";

?>

 

网络来看的,未有看太懂,先转了!

文章来源:威尼斯正规官网,刘俊涛的博客

地址:

款待关心,有题目风姿罗曼蒂克并念书迎接留言、钻探。

本文由威尼斯在线注册平台发布于热门资源,转载请注明出处:PHP如何实现多进程,由于php的进程是不支持多线程的

上一篇: 代码如下 下一篇:以下函数可用于替换php内置的is,你也可以用file
猜你喜欢
热门排行
精彩图文