实现PHP Thread基类

实现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";

 

posted @ 2017-04-19 18:17  hi_felix  阅读(2072)  评论(0编辑  收藏  举报