swoole_process模拟耗时操作

  • 一例串行阻塞操作
<?php
$start = time();
$tasklists = [
    '/root/文档/longtale1.txt',
    '/root/文档/longtale2.txt',
    '/root/文档/longtale3.txt',
    '/root/文档/longtale4.txt',
    '/root/文档/longtale5.txt',
];

function parseurl($path)
{
    sleep(2);  #模拟某些耗时操作
    return "这个文件的文件名是".$path."\n";
}

foreach ($tasklists as $tasklist)
{
    echo parseurl($tasklist);
}
$end = time();
echo "共耗时:".($end-$start);
  • 异步操作
<?php
$start = time();

$tasklists = [
'/root/文档/longtale1.txt',
'/root/文档/longtale2.txt',
'/root/文档/longtale3.txt',
'/root/文档/longtale4.txt',
'/root/文档/longtale5.txt',
];

$processlist=[];

function parseurl($path)
{
sleep(2);
return "要解析的文件名为".$path.PHP_EOL;
}

foreach($tasklists as $tasklist)
{
$process = new swoole_process(function(swoole_process $sw) use($tasklist){
$ret = parseurl($tasklist);
$sw->write($ret);
},false);
$process->start();
array_push($processlist,$process);
}

foreach($processlist as $myprocess)
{
echo $myprocess->read().PHP_EOL;
}

$end = time();
echo "总共耗时".($end-$start);
?>
上一篇:安装swoole


下一篇:swoole(进程,线程)