php多线程扩展pthreads安装使用,swoole多进程,内置多进程

pthreads下载安装教程

https://www.php.net/manual/zh/pthreads.installation.php

使用示例

class pthreadsTest extends Thread {

    public function run () {

        sleep(5);

    }

}

$ts1 = new pthreadsTest();
echo date('Y-m-d H:i:s');
$ts1->start();

$ts2 = new pthreadsTest();

$ts2->start();
echo date('Y-m-d H:i:s');

 

执行完只需要5秒

swoole多进程

echo '开始时间:'.date('H:i:s',time());
//进程数
$work_number=6;
 
//
$worker=[];
 
//模拟地址
$curl=[
    'https://blog.csdn.net/feiwutudou',
    'https://wiki.swoole.com/wiki/page/215.html',
    'http://fanyi.baidu.com/?aldtype=16047#en/zh/manager',
    'http://wanguo.net/Salecar/index.html',
    'http://o.ngking.com/themes/mskin/login/login.jsp',
    'https://blog.csdn.net/marksinoberg/article/details/77816991'
];
 
//单线程模式
// foreach ($curl as $v) {
//     echo curldeta($v);
// }
 
//创建进程
for ($i=0; $i < $work_number; $i++) {
    //创建多线程
    $pro=new swoole_process(function(swoole_process $work) use($i,$curl){
        //获取html文件
        $content=curldeta($curl[$i]);
        //写入管道
        $work->write($content.PHP_EOL);
    },true);
    $pro_id=$pro->start();
    $worker[$pro_id]=$pro;
}
//读取管道内容
foreach ($worker as $v) {
     echo $v->read().PHP_EOL;
}
 
//模拟爬虫
function curldeta($curl_arr)
{    //file_get_contents
    echo $curl_arr.PHP_EOL;
    file_get_contents($curl_arr);
}
 
//进程回收
swoole_process::wait();
 
echo '结束时间:'.date('H:i:s',time());
 
 ?>

 

自带的多进程

//最大的子进程数量
$maxChildPro = 8;

//当前的子进程数量
$curChildPro = 0;

//当子进程退出时,会触发该函数,当前子进程数-1
function sig_handler($sig)
{
    global $curChildPro;
    switch ($sig) {
        case SIGCHLD:
            echo 'SIGCHLD', PHP_EOL;
            $curChildPro--;
            break;
    }
}

//配合pcntl_signal使用,简单的说,是为了让系统产生时间云,让信号捕捉函数能够捕捉到信号量
declare(ticks = 1);

//注册子进程退出时调用的函数。SIGCHLD:在一个进程终止或者停止时,将SIGCHLD信号发送给其父进程。
pcntl_signal(SIGCHLD, "sig_handler");

while (true) {
    $curChildPro++;
    $pid = pcntl_fork();
    if ($pid) {
//父进程运行代码,达到上限时父进程阻塞等待任一子进程退出后while循环继续
        if ($curChildPro >= $maxChildPro) {
            pcntl_wait($status);
        }
    } else {
//子进程运行代码
        $s = rand(2, 6);
        sleep($s);
        echo "child sleep $s second quit", PHP_EOL;
        exit;
    }
}

你可能感兴趣的:(php)