为什么PHP中的一些线程数组操作看起来不起作用?
我有一个使用为什么PHP中的一些线程数组操作看起来不起作用?,php,pthreads,Php,Pthreads,我有一个使用pthreadPHP扩展的线程类: class Task extends Thread { protected $arr = array(); public function run() { $this->arr[] = 1; $this->arr[] = 2; $this->arr[] = 3; var_dump($this->arr); } } $thread
pthread
PHP扩展的线程类:
class Task extends Thread
{
protected $arr = array();
public function run()
{
$this->arr[] = 1;
$this->arr[] = 2;
$this->arr[] = 3;
var_dump($this->arr);
}
}
$thread = new Task();
$thread->start();
$thread->join();
输出令人费解地显示了一个空数组。有人能简要解释一下原因吗?我有一个解决方案,但没有一个可靠的解释,所以欢迎更多的答案 这是我的
线程化的子项(为了简洁起见进行了修剪):
和工人
(再次修剪):
最后,要启动线程:
$thread = new ObjectServer();
$thread->start();
$threaded = new ObjectConstructorThreaded($className, $parameters);
$threaded->setWorker($this->worker);
$thread->stack($threaded);
从我当时写的纯注释中可以看出,插入或推送到数组的尝试失败了,但重写它(通过将其设置为固定值或合并旧值和新条目)似乎可行
因此,我将线程视为使非平凡类型(数组和对象)有效地不可变,并且它们只能重置而不能修改。我对可序列化类也有同样的经验
至于为什么会这样,或者如果有更好的方法,如果我发现了,我会更新这个答案 我怀疑这是一种解释——将实例级数组更改为静态数组,它似乎可以正常工作。此外,还可以对阵列进行建模。
class ObjectServer extends Worker
{
protected $count = 0;
protected $objects = array();
public function notifyObject($object)
{
$key = $this->generateHandle();
/*
// Weird, this does not add anything to the stack
$this->objects[$key] = $object;
// Try pushing - fail!
$this->objects[] = $object;
// This works fine? (but not very useful)
$this->objects = array($key => $object);
*/
// Try adding - also fine!
$this->objects = $this->objects + array($key => $object);
return $key;
}
}
$thread = new ObjectServer();
$thread->start();
$threaded = new ObjectConstructorThreaded($className, $parameters);
$threaded->setWorker($this->worker);
$thread->stack($threaded);