使用pthreads的PHP多线程,类没有在Thread实例中加载

时间:2013-12-22 20:13:21

标签: php multithreading pthreads

所以我使用pthreads来异步写入MongoDB(我想尝试React但它不支持PUT和POST HTTP方法)但是在使用Thread类时我遇到了一个问题。出于某种原因,当我将代码放在__construct()和run()方法中时,执行它会给出一个错误,即找不到某些类。我正在使用相同的Composer自动加载器,并且在我不使用Threading API时没有问题。关于它为什么会发生的任何想法?

<?php

class WriterThread extends Thread
{
    private $validator;
    private $pathResolver;
    private $fileUpload;
    private $fileSystem;
    public $result;
  public function __construct($folderPath, $mongoFS)
  {
      try {

      $this->validator = new MongoFileSystemValidator(1024 * 1024 * 1024 * 2); //the maximum size set to 2GB
        // Simple path resolver, where uploads will be put
        $this->pathResolver = new FileUpload\PathResolver\Simple($folderPath);
        // The machine's filesystem
        $this->fileSystem = new MongoFS($mongoFS);

        // FileUploader itself

        $this->fileUpload = new FileUpload\FileUpload($_FILES['files'], $_SERVER);
        //var_dump(get_declared_classes());
        $this->fileUpload->setPathResolver($this->pathResolver);
        $this->fileUpload->setFileSystem($this->fileSystem);
        $this->fileUpload->addValidator($this->validator);
      } catch (Exception $e) {
          echo $e->getMessage();
      }

  }
  public function run()
  {
      $this->result = $this->fileUpload->processAll();
  }
}

因此,PHP输出一个错误,指出在应该加载时,找不到我在线程中使用的一个类实例的类定义。如果我用include或require手动导入它,代码会输出另一个错误,指出我正在尝试访问非对象类型变量的方法。

1 个答案:

答案 0 :(得分:7)

在编写pthreads应用程序时,默认情况下,在创建线程时会继承类,函数和常量表。但是,SPL自动加载机制,因为它实现奇怪 - 一半在核心,一半在外 - 必须重置,因为没有理智的方法来从pthreads扩展中操作它。

解决方案是将您的自动加载代码包含在:: run中,通常是vendor / autoload.php,您应该知道应用程序的代码路径。

TLDR;类表是可用的,自动加载器不是,包括它......

除自动加载器问题外,该对象的构造还不健全,请阅读:https://gist.github.com/krakjoe/6437782