实现PHP Thread基类

class Thread {

    public function __construct() {

    }

    public function run() {

    }

    public function start() {
        $pid = pcntl_fork();
        if($pid == -1) {
            echo "error";
            die;
        }
        else if ($pid > 0) {

        }
        else {
            $this->run();
            posix_kill(posix_getpid(), SIGTERM);
            exit(0);
        }
    }

    public function join() {
        $childPid = pcntl_wait($status);
        if ($childPid <= 0) {
            exit();
        }
        if ($status == SIGTERM) {
        }
    }
}

class ChildThread extends Thread {
    public $name;
    public function __construct($name)
    {
        $this->name = $name;
    }

    public function run() {
        for($i = 0; $i < 10; $i++) {
            echo $this->name . " " . $i . "\n";
            sleep(1);
        }
    }
}
$arr = array("a", "b", "c");
$threads = array();
foreach ($arr as $name) {
    $child = new ChildThread($name);
    $child->start();
    $threads[] = $child;
}
foreach($threads as $thread) {
    $thread->join();
}
echo "success";

 

相关文章:

  • 2021-11-12
  • 2021-06-28
  • 2021-09-02
  • 2022-01-24
  • 2021-06-13
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2022-01-19
  • 2021-11-04
  • 2021-09-17
  • 2021-09-28
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案