【问题标题】:Read multiple CSV files simultaneously (multithreading) using PHP Pthread使用 PHP Pthread 同时读取多个 CSV 文件(多线程)
【发布时间】:2016-06-01 05:12:14
【问题描述】:

我正在尝试使用 pthread 在 PHP 中实现多线程。 我想要做的是,假设我有 50 个 CSV 文件,其中有很多行要处理。在检查了一些验证标准后,我需要读取每一行并将其插入数据库。因此,我不想一次读取一个文件,而是一次创建 5 个多个线程,它们将同时处理 5 个不同的文件。如果任何一个线程首先完成,下一个排队的文件将加入该线程。

例如。我有 1X.CSV 到 50X.CSV 我将启动 5 个线程来处理 1X.CSV 到 5X.CSV。现在 3X.CSV 与其他四个文件相比非常小。所以它的处理首先完成。所以第 3 个线程获得空闲,它将寻找下一个排队的文件,即 6X.CSV。每个线程将单独工作。

我的问题是,当我在不读取文件的情况下进行多线程时,它工作得很好!但是 fopen() 并不能帮助我在 run() 函数中读取文件。谁能告诉我哪里出错了?下面是我的代码。任何帮助将不胜感激。

class AsyncLongAction extends Thread 
{

  public function __construct($s,$file)
  {
      $this->s = $s;
      $this->file = $file;
      //echo $file."<BR>";
  }

  public function run()
  {
     if($this->s)
     {
         printf("TID: %s is waiting for %s %s ...\n", $this->getCurrentThreadId(), $this->s, $this->file);
         //sleep($this->s);
         printf("%ss is over.\n<br>", $this->s);

         $handle = fopen($this->file,"r");
         echo $handle; //It is not giving any result.
         while(($filesop = fgetcsv($handle,1000,",")) != false)
         {
              $name = $filesop[0];
              $times = time();
              $sql = "<BR>".$name."---".$times."======".Thread::getCurrentThreadId();
              echo $sql;
         }
      fclose($handle);
     }
  }
}

$thread = array();
$files = glob("CSV/*"); // path is right, I have tried working with the same code without using pthread.

foreach($files as $key=>$file)
{
   $thread[] = new AsyncLongAction($key+1,$file);
}

$c= 0;
foreach($thread as $st)
{
    if($c < 3)
       $st->start();
    $st->join();
    $c++;
}

【问题讨论】:

  • 尝试回显$this-&gt;file,您似乎没有在线程内的fopen函数中获得file
  • 已经试过了。它正在过去!

标签: php multithreading csv pthreads fopen


【解决方案1】:

您启动一个线程,然后立即等待它完成。然后你开始下一个,依此类推...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-07
    • 2020-09-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多