最近使用扩展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! …