我正在使用php5.4,并提供以下代码进行测试。我将一个对象传递给一个工作线程,并尝试修改线程中的对象,这对象没有按预期工作。
<?php
class WorkerThread extends Thread {
var $foo = null;
public function __construct($foo) {
$this->foo = $foo;
}
public function run() {
echo "thread started.\n";
$this->foo->val = 2;
echo "\n";
echo $this->foo->val;
echo "\n";
echo "thread exit${val}.\n";
}
}
class A {
var $val = 1;
}
$foo = new A();
var_dump($foo);
$thread = new WorkerThread($foo);
$thread->start();
sleep(1);
var_dump($foo);
$foo2 = $foo;
$foo2->val = 3;
var_dump($foo);
?>
这是我得到的输出:
object(A)#1 (1) {
["val"]=>
int(1)
}
thread started.
1 # I expect 2 here
thread exit.
object(A)#1 (1) {
["val"]=>
int(1) # I expect 2 here
}
object(A)#1 (1) { # as expected
["val"]=>
int(3)
}
如果我不能在线程之间共享对象,那么什么是互斥锁,cond是为什么设计的?