欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  资讯频道

swoole 1.7.3发布,增加PHP多进程管理模块

程序员文章站 2022-04-18 10:58:30
...

PHP的异步并行扩展swoole,最近增加了多进程管理模块swoole_process,用来替代PHP的pcntl扩展。

 

PHP自带的pcntl,存在很多不足,如:

 

  • pcntl无法用在fpm/apache中
  • pcntl没有提供进程间通信的功能
  • pcntl不支持重定向标准输入和输出
  • pcntl只提供了fork这样原始的接口,容易使用错误

swoole_process提供了比pcntl更强大的功能,更易用的面向对象风格API,使PHP在多进程编程方面更加轻松。

 

swoole_process提供的功能特性:

 

  • swoole_process提供了基于unixsock的进程间通信,使用很简单只需调用recv/send即可
  • swoole_process支持重定向标准输入和输出,在子进程内echo不会打印屏幕,而是写入管道,读键盘输入可以重定向为管道读取数据
  • swoole_process允许用于fpm/apache的Web请求中
  • 配合swoole_event模块,创建的PHP子进程可以异步的事件驱动模式
  • swoole_process提供了exec接口,创建的进程可以执行其他程序,与原PHP父进程之间可以方便的通信
  • swoole_process可以安全地用于fpm/apache环境下

代码示例:

$worker_num = 8;

for($i = 0; $i < $worker_num; $i++)
{
    $process = new swoole_process('callback_function', true);
    $pid = $process->start();
    $workers[$pid] = $process;
}

foreach($workers as $pid => $process)
{
    $process->write("hello worker[$pid]\n");
    echo "From Worker: ".$process->read();
}

for($i = 0; $i < $worker_num; $i++)
{
    $ret = swoole_process::wait();
    $pid = $ret['pid'];
    unset($workers[$pid]);
    echo "Worker Exit, PID=".$pid.PHP_EOL;
}

function callback_function(swoole_process $worker)
{
    //echo "Worker: start. PID=".$worker->pid."\n";
    //recv data from master
    $recv = $worker->read();
    echo "From Master: $recv\n";

    //send data to master
    $worker->write("hello master\n");

    sleep(2);
    $worker->exit(0);
}

 

子进程事件驱动模式

function callback_function_async(swoole_process $worker)
{
    //echo "Worker: start. PID=".$worker->pid."\n";
    //recv data from master
    $GLOBALS['worker'] = $worker;
    swoole_event_add($worker->pipe, function($pipe) {
        $worker = $GLOBALS['worker'];
        $recv = $worker->read();

        echo "From Master: $recv\n";

        //send data to master
        $worker->write("hello master\n");

        sleep(2);

        $worker->exit(0);
    });
}

 

PHP创建一个Python子进程,并与之通信

$process = new swoole_process('pyhon_process', true);
$pid = $process->start();

function pyhon_process(swoole_process $worker)
{
    $worker->exec('/usr/bin/python', array("echo.py"));
}

$process->write("hello world\n");
echo $process->read();

$ret = swoole_process::wait();
var_dump($ret);

 

Python程序echo.py

import sys

def main():
	s = raw_input()
	print "Python:" + s

main()