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

时间:2014-10-01 21:00:37

标签: php pthreads

我有这个使用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();

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

1 个答案:

答案 0 :(得分:0)

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

这是我的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);

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

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

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