相关疑难解决方法(0)

pthread线程对象重置其状态

最近使用扩展pthreads工作,我发现了一个异常现象.我有一个内部状态的简单对象:

class Sum {
    private $value = 0;
    public function add($inc)  { $this->value += $inc; }
    public function getValue() { return $this->value; }
}
Run Code Online (Sandbox Code Playgroud)

现在我创建了一个Thread类,它对这个对象做了一些事情:

class MyThread extends Thread {
    private $sum;

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

    public function run(){
        for ($i=0; $i < 10; $i++) {
            $this->sum->add(5);
            echo $this->sum->getValue() . " ";
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

在我的main函数中,我创建了一个Sum对象,将其注入到线程中并启动它:

$sum = new Sum();
$thread = new MyThread($sum);
$thread->start();
$thread->join();
echo $sum->getValue();
Run Code Online (Sandbox Code Playgroud)

我期望结果是50,因为线程必须将值增加10倍.但是我得到了0! …

php multithreading pthreads shared-memory

8
推荐指数
1
解决办法
5119
查看次数

标签 统计

multithreading ×1

php ×1

pthreads ×1

shared-memory ×1