Swoole多进程的实现

1 篇文章 0 订阅
1 篇文章 0 订阅
/**
 * 使用swoole多进程上传文件到网宿服务器
 * Created by PhpStorm.
 * User: leeo
 * Date: 2016/9/29
 * Time: 15:26
 */
// 引入文件上传类
include_once "FileHandleClass.php";
$obj_fetch = new FileHandleClass();

$workers = [];
$worker_num = 2;

// 清空上次的日志文件
if(file_exists("logs/push.log")){
    file_put_contents("logs/push.log","");
}
if(file_exists("logs/pop.log")){
    file_put_contents("logs/pop.log","");
}

$filename = "data/2015-06-test.txt";// 需要上传的文件信息集合
$stream = file_get_contents($filename);
$data = json_decode($stream,true);
$total = count($data);
$every = intval($total / $worker_num) + 1;  // 每个进程需要循环的次数

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

function callback_function(swoole_process $worker){
    global $obj_fetch;
    while($recv = $worker->pop()){
        file_put_contents("logs/pop.log",$recv."\r\n",FILE_APPEND);
        $recv = json_decode($recv,true);
        $obj_fetch->fetch($recv['full_path'],$recv['file_name']);
    }
    echo $worker->callback .'--'.$worker->pipe.PHP_EOL;
    $worker->exit(0);
}

// 将资源存入队列中
$n = 0;
foreach($workers as $pid => $process){
    if($n == $worker_num - 1){
        $ret = array_slice($data,$n*$every);
    }else{
        $ret = array_slice($data,$n*$every,$every);
    }
    foreach($ret as $k=>$v){
        $kv = json_encode($v);
        $process->push($kv);
        file_put_contents("logs/push.log",$kv."\r\n",FILE_APPEND);
    }
    $n++;
}

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值