PHP:在单独的线程中运行类方法

4

在PHP中,是否可能在单独的线程中运行一个类的方法?
例如:
线程:

class AsyncThread extends \Thread {

    private $method;
    private $obj;
    private $params;
    private $timeout;

    public function __construct($obj, $method, $params, $timeout){
        $this->obj    = $obj;
        $this->method = $method;
        $this->params = $params;
        $this->timeout = $timeout;
    }

    public function run() {
        sleep($this->timeout);
        if (call_user_func_array([$this->obj, $this->method], $this->params)) {
            return true;
        } else return false;
    }
}  

类:

class MyClass {

    private $param = 'username';

    public function callThread() {
        $thread = new AsyncThread($this, 'threadMethod', ['hello'], 5);
    }

    public function threadMethod($param) {
        echo "{$param} {$this->param}";
    }

}

当我尝试调用一个名为callThread的方法时,出现错误:

$obj = new MyClass();
$obj->callThread();

Serialization of 'Closure' is not allowed

还有什么其他的方法可以启动线程,以便流程可以访问MyClass对象类的方法?


我不认为这是重复的。我问了一个关于如何在单独的线程中运行类方法的问题。 - Eugene
1个回答

2
我认为你正在寻找的是pthreads,来自PHP DOC:

pthreads是一个面向对象的API,允许在PHP中进行用户级多线程。它包括创建针对Web或控制台的多线程应用程序所需的所有工具。 PHP应用程序可以创建、读取、写入、执行和与线程、工人和线程化对象同步。

线程化对象:线程化对象构成了pthreads运行的基础。它公开了同步方法和一些对程序员有用的接口。

这是它在GitHub - PHTREADS上的链接。


谢谢。我了解了pthread,但是我还没有找到我的问题的答案。如果您能在这里给出一个例子,那就太好了。 - Eugene

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接