PHP pthread似乎不是多线程的 [英] PHP pthread doesnt seems to be multithreading

查看:66
本文介绍了PHP pthread似乎不是多线程的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请尽可能提供帮助.我打算从数据库中提取X数量的行,将它们分成20个数组的数组,然后将它们传递给线程以同时进行处理.

Please assist if possible. I intended to pull an X amount of rows from a DB, separating them into arrays of 20 arrays and pass them to a thread for processing simultaneously.

为确保该进程同时工作,我创建了一个快速线程,该线程回显出线程号,然后计数为20.我希望看到类似"1 at 1"然后"2 at 1"的结果.相反,我看到在第二个线程开始执行之前,第一个线程计数到20.即"1在1" ..."1在20"然后只有"2在1".

To ensure the process was working simultaneously i created a quick thread that echo's out the thread number then counts to 20. I expected to see results like "1 at 1" then "2 at 1". Instead i see the first thread counts to 20 before the second thread begins to execute. ie "1 at 1" ... "1 at 20" then only "2 at 1".

<?php
class helloworld extends Thread {
    public function __construct($arg){
        $this->arg = $arg;
    }
    public function run(){
        if($this->arg){
            for ($i=1;$i<=20;$i++){
                echo $this->arg ." AT ";
                echo $i." ";
                sleep(1);
            }
        }
    }
}

?>

然后称呼我

for ($i=1;$i<=$num_threads;$i++){
    $thread[$i] = new helloworld($i);
    if($thread[$i]->start())
        $thread[$i]->join();
}

我看到的是正确的吗?还是我在这里做一些愚蠢的事情?

Is what i am seeing correct? Or am i doing something stupid here?

谢谢

Rob

推荐答案

pthread的join()函数等待指定的线程终止.如果该线程已经终止,则pthread的join()函数将立即返回.指定的线程必须是可连接的.

The pthread's join() function waits for the thread specified to terminate. If that thread has already terminated, then pthread's join() function returns immediately. The thread specified must be joinable.

因此,在循环中继续操作之前,您正在等待每个启动的线程终止.

So, you are waiting for each started thread to terminate before moving on in your loop.

这篇关于PHP pthread似乎不是多线程的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆