为什么PHP中的一些线程数组操作似乎不起作用


Why do some threaded array operations in PHP appear not to work?

我有一个线程类,它使用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();

输出莫名其妙地显示了一个空数组。有人能简要解释一下原因吗?

我有一个解决方案,但没有一个可靠的解释,所以欢迎更多的答案。

这是我的Threaded孩子(为了简洁起见,对其进行了修剪):

class ObjectConstructorThreaded extends Threaded
{
    protected $worker;
    protected $className;
    protected $parameters;
    protected $objectKey;
    public function __construct($className, $parameters)
    {
        $this->className = $className;
        $this->parameters = $parameters;
    }
    public function setWorker('Worker $worker)
    {
        $this->worker = $worker;
    }
    protected function getWorker()
    {
        return $this->worker;
    }
    public function run()
    {
        $reflection = new 'ReflectionClass($this->className);
        $instance = $reflection->newInstanceArgs($this->parameters);
        $this->objectKey = $this->getWorker()->notifyObject($instance);
    }
    public function getObjectKey()
    {
        return $this->objectKey;
    }
}

Worker(再次修剪):

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);

从我当时写的纯注释中可以看出,插入或推送到数组的尝试失败了,但重写它(通过将其设置为固定值或将旧值和新项合并)似乎有效。

因此,我将线程化视为使非平凡类型(数组和对象)有效地不可变,并且它们只能重置而不能修改。我对可序列化类也有同样的经历。

至于为什么会出现这种情况,或者如果有更好的方法,如果我发现了,我会更新这个答案!