导航菜单

并发与异步编程

多进程

  • 进程创建与管理。
  • 进程间通信。
  • 进程池。
<?php
// 多进程示例

// 1. 基本进程创建
function create_process($callback) {
    $pid = pcntl_fork();
    if ($pid == -1) {
        die("无法创建子进程");
    } elseif ($pid) {
        // 父进程
        return $pid;
    } else {
        // 子进程
        $callback();
        exit(0);
    }
}

// 2. 进程池示例
class ProcessPool {
    private $size;
    private $processes = [];

    public function __construct($size) {
        $this->size = $size;
    }

    public function start($callback) {
        for ($i = 0; $i < $this->size; $i++) {
            $pid = pcntl_fork();
            if ($pid == -1) {
                die("无法创建子进程");
            } elseif ($pid) {
                $this->processes[$pid] = true;
            } else {
                $callback($i);
                exit(0);
            }
        }
    }

    public function wait() {
        while (count($this->processes) > 0) {
            $pid = pcntl_wait($status);
            if ($pid > 0) {
                unset($this->processes[$pid]);
            }
        }
    }
}

// 3. 进程间通信
// 使用共享内存
function shared_memory_example() {
    $key = ftok(__FILE__, "t");
    $shm_id = shmop_open($key, "c", 0644, 100);

    if (pcntl_fork() == 0) {
        // 子进程写入数据
        shmop_write($shm_id, "Hello from child", 0);
        exit(0);
    } else {
        // 父进程读取数据
        pcntl_wait($status);
        $data = shmop_read($shm_id, 0, 100);
        echo $data;
        shmop_delete($shm_id);
        shmop_close($shm_id);
    }
}

// 4. 信号处理
function signal_handler($signo) {
    switch ($signo) {
        case SIGTERM:
            echo "收到终止信号
";
            exit(0);
            break;
        case SIGCHLD:
            echo "子进程结束
";
            pcntl_waitpid(-1, $status);
            break;
    }
}

pcntl_signal(SIGTERM, "signal_handler");
pcntl_signal(SIGCHLD, "signal_handler");
?>