zoukankan      html  css  js  c++  java
  • 用文件实现计算器要求多进程同时写

    用文件实现一个计算器,要求可满足多进程同时写,最后得出结果。以下为代码:

    <?php
    $path = 'board.txt';
    touch($path);
    $max = isset($argv[1]) ? $argv[1] : 100;
    for($i = 0;$i < $max;$i++) {
        $pids[$i] = pcntl_fork();
        if($pids[$i] > 0) {
        } else if($pids[$i] == 0) {
            while(1) {
                $fp = fopen($path,'r+');
                if($fp) {
                    $lock = flock($fp,LOCK_EX);
                    if($lock) {
                        $num1 = fread($fp,4096);
                        $num2 = intval($num1) + 1;
                        fseek($fp,0,SEEK_SET);
                        fwrite($fp,$num2);
                        flock($fp,LOCK_UN);
                        fclose($fp);
                        break;
                    }
                    fclose($fp);
                }
            }
            exit(0);
        } else {
            echo "fail to fork a pid
    ";
        }
    }
    
    while(count($pids) > 0) {
        foreach($pids as $key => $pid) {
            $res = pcntl_waitpid($pid, $status, WNOHANG);
            // If the process has already exited
            if($res == -1 || $res > 0)
                unset($pids[$key]);
        }
        sleep(1);
    }
    $result = file_get_contents($path);
    echo 'result is : ',$result,"
    ";
    unlink($path);
  • 相关阅读:
    Go标准库之tar
    redis必知必会
    GORM CRUD指南
    GORM入门指南
    MUI中tap点击事件点击一次连续申请两次
    Go代码启动默认浏览器
    Go实现JWT
    Go Micro
    protobuf初识
    英语作文
  • 原文地址:https://www.cnblogs.com/lrxing/p/4704934.html
Copyright © 2011-2022 走看看