V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
gouchaoer
V2EX  ›  PHP

swoole 新的 api 文件协程: co::fread 和 co::fwrite 函数

  •  
  •   gouchaoer · 2017-12-21 16:47:16 +08:00 · 1781 次点击
    这是一个创建于 2289 天前的主题,其中的信息可能已经有所发展或是发生改变。

    swoole server 里面也好,或者单纯的 php-cli 脚本里也好,现在可以像 go 那样写重磁盘 IO 的任务了,举个例子: 往 2500 个文件中分别写入 1KB 的数据

    <?php
    use Swoole\Coroutine as co;
    
    ini_set('memory_limit', -1); 
    $ct=0;
    
    for($i=0;$i<2500;$i++)
    {
    co::create(function () use (&$ct)
    {
        $uid = \Swoole\Coroutine::getuid();
        $fp = fopen(__DIR__ . "/test/{$uid}", "a+");
        $str='';   
        for($j=0;$j<1024;$j++)$str.='1';//1K
        $r =  co::fwrite($fp, $str);
        $ct++;
        //echo "|{$ct}";
    });
    }
    
    function shutdown()
    {
    global $ct;
    echo "ct:{$ct}, mem_peak:".memory_get_peak_usage().", mem:".memory_get_usage().PHP_EOL;
    }
    
    register_shutdown_function('shutdown');
    

    php fwrite.php

    ct:2500, mem_peak:665626736, mem:513288

    0.5s 内完成

    gouchaoer
        1
    gouchaoer  
    OP
       2017-12-21 16:49:10 +08:00
    不过每个协程的裸内存开销是 266KB 左右,没有 go 那样占用内存小
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   3357 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 11:22 · PVG 19:22 · LAX 04:22 · JFK 07:22
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.