1
我正尝试在PHP中使用pthread实现多线程。 我想要做的是,假设我有50个CSV文件,有许多行可供使用。我需要阅读每一行,并在检查一些验证条件后将其插入数据库。因此,我不想一次读取一个文件,而是希望在时间创建5个多个线程,这将同时处理5个不同的文件。如果任何线程先完成,下一个排队的文件将加入该线程。使用PHP Pthread同时读取多个CSV文件(多线程)
例如,我有1X.CSV到50X.CSV 我将启动5个线程来处理1X.CSV到5X.CSV。现在3X.CSV与其他四个文件相比非常小。所以它的处理首先完成。所以第三个线程可以免费使用,它会查找下一个排队的文件,例如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++;
}
尝试echo'$ this-> file'看起来你没有在'fopen'函数内获得'file'内线程 –
已经尝试过。它正在越过! –