php中关于线程thread的使用

来源:互联网 发布:暗黑2 1.13 完美 mac 编辑:程序博客网 时间:2024/06/05 07:07

【原文:http://www.01happy.com/php-thread-introduction/】


php通过扩展pthreads也可以支持线程上的操作,在mac下可以通过brew安装pthreads扩展。

安装pthreads扩展

搜索pthreads

$ brew search pthreads homebrew/php/php53-pthreads homebrew/php/php54-pthreads homebrew/php/php55-pthreads homebrew/php/php56-pthreads

根据不同的php版本进行安装,例如我是安装php55-pthreads

$ brew install php55-pthreads

安装完成后,记的重启下web服务器。

线程测试

线程类要继承Thread类,而后实现run方法。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
classcomputer extendsThread {
 
    public$id;
    public$runing = false;
    public$params = null;
 
    publicfunction __construct($id) {
        $this->id     = $id;
        $this->runing = true;
    }
 
    publicfunction run() {
        while($this->runing) {
            if(is_null($this->params)) {
                echo"线程({$this->id})等待任务...\n";
            else{
                echo"线程({$this->id}) 收到任务参数::{$this->params}.\n";
                $this->params = null;
            }
            sleep(1);
        }
    }
 
}

代码很简单,用running标记线程是否在运行,params标记外界传递的参数,如果外界传递参数过来则可以运行。

使用该类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
//这里创建线程池.
$poolarray(newcomputer('a'), newcomputer('b'), newcomputer('c'));
 
//启动所有线程,使其处于工作状态
foreach($poolas $w) {
    $w->start();
}
 
//派发任务给线程
for($i= 0; $i< 10; $i++) {
    $params= rand(10, 99);
    while(true) {
        foreach($poolas $worker) {
            //参数为空则说明线程空闲
            if(is_null($worker->params)) {
                $worker->params = $params;
                echo"({$worker->id})线程空闲,放入参数{$params}.\n";
                break2;
            }
        }
        sleep(1);
    }
}
 
//关闭线程
while(count($pool)) {
    //遍历检查线程组运行结束
    foreach($poolas $key => $worker) {
        if($worker->params == '') {
            echo"({$worker->id})线程运行完成,退出.\n";
            //设置结束标志
            $worker->runing = false;
            unset($pool[$key]);
        }
    }
    echo"等待退出中...\n";
    sleep(1);
}
 
echo"退出成功\n";

运行结果

在命令行中运行输入结果参考如下:

$ php thread.php线程(a)等待任务...线程(b)等待任务...线程(c)等待任务...(a)线程空闲,放入参数21.(b)线程空闲,放入参数97.(c)线程空闲,放入参数54.线程(a) 收到任务参数::21.线程(b) 收到任务参数::97.线程(c) 收到任务参数::54.(a)线程空闲,放入参数68.(b)线程空闲,放入参数71.(c)线程空闲,放入参数58.线程(a) 收到任务参数::68.线程(b) 收到任务参数::71.线程(c) 收到任务参数::58.(a)线程空闲,放入参数79.(b)线程空闲,放入参数20.(c)线程空闲,放入参数18.线程(a) 收到任务参数::79.线程(b) 收到任务参数::20.线程(c) 收到任务参数::18.(a)线程空闲,放入参数76.(b)线程运行完成,退出.(c)线程运行完成,退出.线程(a) 收到任务参数::76.等待退出中...线程(a)等待任务...(a)线程运行完成,退出.等待退出中...退出成功

因为使用了sleep,在浏览器里运行估计要等结果输出需要一段时间。这里还有一个问题可以考虑一下:这里的线程工作任务只是输出内容,如果需要得到返回的计算结果,和普通的函数调用返回不同,这里涉及到异步方面的问题,会复杂一些,后续再介绍吧。


原创粉丝点击