我们可以通过安装Pthread扩展来让PHP支持多线程。

 
线程,有时称为轻量级进程,是程序执行的最小单元。线程是进程中的一个实体,是被系统独立调度和分派的基本单位,线程自己不拥有系统资源,它与同属一个进程的其它线程共享进程所拥有的全部资源。一个线程可以创建和撤消另一个线程,同一进程中的多个线程之间可以并发执行。每一个程序都至少有一个线程,那就是程序本身,通常称为主线程。线程是程序中一个单一的顺序控制流程。 在单个程序中同时运行多个线程完成不同的工作,称为多线程。
  1. <?php
  2.  
  3. //实现多线程必须继承Thread类
  4. class test extends Thread {
  5. public function __construct($arg){
  6. $this->arg = $arg;
  7. }
  8.  
  9. //当调用start方法时,该对象的run方法中的代码将在独立线程中异步执行。
  10. public function run(){
  11. if($this->arg){
  12. printf("Hello %s\n", $this->arg);
  13. }
  14. }
  15. }
  16. $thread = new test("World");
  17.  
  18. if($thread->start()) {
  19. //join方法的作用是让当前主线程等待该线程执行完毕
  20. //确认被join的线程执行结束,和线程执行顺序没关系。
  21. //也就是当主线程需要子线程的处理结果,主线程需要等待子线程执行完毕
  22. //拿到子线程的结果,然后处理后续代码。
  23. $thread->join();
  24. }
  25. ?>

我们把上述代码修改一下,看看效果

  1. <?php
  2.  
  3. class test extends Thread {
  4. public function __construct($arg){
  5. $this->arg = $arg;
  6. }
  7. public function run(){
  8. if($this->arg){
  9. sleep(3);
  10. printf("Hello %s\n", $this->arg);
  11. }
  12. }
  13. }
  14. $thread = new test("World");
  15.  
  16. $thread->start();
  17.  
  18. echo "main thread\r\n";
  19. ?>

我们直接调用start方法,而没有调用join。主线程不会等待,而是在输出main thread。子线程等待3秒才输出Hello World。

 
例1如下:
  1. <?php
  2. class test extends Thread {
  3. private $name = '';
  4. private $res = null;
  5.  
  6. public function __construct($name, $res){
  7. $this->name = $name;
  8. $this->res = $res;
  9. }
  10. public function run(){
  11. while(!feof($this->res)) {
  12. if(flock($this->res, LOCK_EX)) {
  13. $data = fgets($this->res);
  14. $data = trim($data);
  15. echo "Thread {$this->name} Read {$data} \r\n";
  16. sleep(1);
  17. flock($this->res, LOCK_UN);
  18. }
  19. }
  20. }
  21. }
  22.  
  23. $fp = fopen('./test.log', 'rb');
  24.  
  25. $threads[] = new test('a', $fp);
  26. $threads[] = new test('b', $fp);
  27.  
  28. foreach($threads as $thread) {
  29. $thread->start();
  30. }
  31.  
  32. foreach($threads as $thread) {
  33. $thread->join();
  34. }
  35. ?>

我们通过创建两个线程a和b来读取文件test.log中的内容。(*注意,在并发读写文件时,一定要给文件加锁。这里给文件加上独占锁,如果加共享锁会出现读取相同数据。)

test.log的内容如下:
  1. 111111
  2. 222222
  3. 333333
  4. 444444
  5. 555555
  6. 666666

执行结果如下:

 
例2如下:
  1. <?php
  2. class Total extends Thread {
  3. public $name = '';
  4. private $total = 0;
  5. private $startNum = 0;
  6. private $endNum = 0;
  7.  
  8. public function __construct($name, $startNum, $endNum){
  9. $this->name = $name;
  10. $this->startNum = $startNum;
  11. $this->endNum = $endNum;
  12. }
  13. public function run(){
  14. for($ix = $this->startNum; $ix < $this->endNum; ++$ix) {
  15. $this->total += $ix;
  16. }
  17. echo "Thread {$this->name} total: {$this->total} \r\n";
  18. }
  19. public function getTotal() {
  20. return $this->total;
  21. }
  22. }
  23.  
  24. $num = 10000000;
  25. $threadNum = 10;
  26. $setp = $num / $threadNum;
  27. $startNum = 0;
  28.  
  29. $startTime = microtime(true);
  30. for($ix = 0; $ix < $threadNum; ++$ix) {
  31. $endNum = $startNum + $setp;
  32. $thread = new Total($ix, $startNum, $endNum);
  33. $thread->start();
  34. $startNum = $endNum;
  35. $threads[] = $thread;
  36. }
  37.  
  38. $total = 0;
  39. foreach($threads as $thread) {
  40. $thread->join();
  41. $total += $thread->getTotal();
  42. }
  43.  
  44. $endTime = microtime(true);
  45. $time = $endTime - $startTime;
  46.  
  47. echo "total : {$total} time : {$time} \r\n";

我们通过创建10个线程,分别计算累加和,而后主线程把10个线程计算的结果统一相加得到最后结果。

我们不使用多线程,来计算这累加和,代码如下:

  1. <?php
  2. $total = 0;
  3.  
  4. $startTime = microtime(true);
  5.  
  6. for($ix = 0; $ix < 10000000; ++$ix) {
  7. $total += $ix;
  8. }
  9.  
  10. $endTime = microtime(true);
  11. $time = $endTime - $startTime;
  12.  
  13. echo "total : {$total} time : {$time} \r\n";

我们可以看到使用多线程和不使用,得到的结果是一样的,但是处理时间,多线程就慢很多。(*主要是线程的创建也是需要资源的,而且线程之间的相互切换也需要时间,这里的例子主要说明如何把一个问题分配给多个子线程去处理,然后主线程拿到子线程的结果并处理得到我们需要的结果。)

 
 
 
 

php Pthread 多线程 (一) 基本介绍的更多相关文章

  1. pthread多线程编程的学习小结

    pthread多线程编程的学习小结  pthread 同步3种方法: 1 mutex 2 条件变量 3 读写锁:支持多个线程同时读,或者一个线程写     程序员必上的开发者服务平台 —— DevSt ...

  2. clone的fork与pthread_create创建线程有何不同&pthread多线程编程的学习小结(转)

    进程是一个指令执行流及其执行环境,其执行环境是一个系统资源的集合,这些资源在Linux中被抽 象成各种数据对象:进程控制块.虚存空间.文件系统,文件I/O.信号处理函数.所以创建一个进程的 过程就是这 ...

  3. iOS开发多线程篇—GCD介绍

    iOS开发多线程篇—GCD介绍 一.简单介绍 1.什么是GCD? 全称是Grand Central Dispatch,可译为“牛逼的中枢调度器” 纯C语言,提供了非常多强大的函数 2.GCD的优势 G ...

  4. VC++6.0 下配置 pthread库2010年12月12日 星期日 13:14VC下的pthread多线程编程 转载

    VC++6.0 下配置 pthread库2010年12月12日 星期日 13:14VC下的pthread多线程编程     转载 #include <stdio.h>#include &l ...

  5. C语言使用pthread多线程编程(windows系统)二

    我们进行多线程编程,可以有多种选择,可以使用WindowsAPI,如果你在使用GTK,也可以使用GTK实现了的线程库,如果你想让你的程序有更多的移植性你最好是选择POSIX中的Pthread函数库,我 ...

  6. php Pthread 多线程基本介绍

    我们可以通过安装Pthread扩展来让PHP支持多线程.   线程,有时称为轻量级进程,是程序执行的最小单元.线程是进程中的一个实体,是被系统独立调度和分派的基本单位,线程自己不拥有系统资源,它与同属 ...

  7. 多线程02---pThread简单介绍

    1.简单介绍 pthread 是属于 POSIX 多线程开发框架. 它是c语言提供的一个跨平台的多线程解决方式.因为其在iOS编程中,操作比較麻烦.一般不用,这里介绍只作为了解. 2.pthread的 ...

  8. pthread 多线程基础

    本文主要介绍如何通过 pthread 库进行多线程编程,并通过以下例子进行说明. 基于莱布尼兹级数计算 \(\pi\) . 多线程归并排序 参考文章: [1] https://computing.ll ...

  9. NDK中使用pthread多线程中自己写的一个BUG

    在使用pthread进行NDK中的多线程开发时,自己写了一个BUG, void *darkGrayThread(void *args) { ThreadParam *param = (ThreadPa ...

随机推荐

  1. cmd命令总结

    1.进入d盘 2.命令运行D:\mongodb\bin中的mongod.exe  显示安装成功!(命令行下运行 MongoDB 服务器)

  2. GlusterFS PERFORMANCE TUNING

    众所周知,glusterfs对小文件而言,就是个鸡肋,特别是在一个目录下有过W的小文件图片时,ls简单就是个坑,下面我对线上的glusterfs参数做一些优化调整,调整的命令: gluster vol ...

  3. 属性,类方法@classmethod

    # 属性的初识# class Person:## def __init__(self,name,hight,weight):# self.name = name# self.__hight = hig ...

  4. tensorboard-sklearn数据-loss

    记录sklearn数据训练时的loss值,用tensorboard可视化 三步骤:红字处 import tensorflow as tf from sklearn.datasets import lo ...

  5. jar包双击执行引用外部包问题

    大家都知道一个java应用项目可以打包成一个jar,当然你必须指定一个拥有main函数的main class作为你这个jar包的程序入口. 具体的方法是修改jar包内目录META-INF下的MANIF ...

  6. 学习笔记:Zepto笔记

    1.Zepto对象不能自定义事件 例如执行:$({}).bind('cust',function(){}); 结果:TypeError:Object#hasnomethod'addEventListe ...

  7. php上传文件涉及到的参数

          php上传文件涉及到的参数: 几个参数调整: 0:文件上传时存放文件的临时目录.必须是 PHP 进程所有者用户可写的目录.如果未指定则 PHP 使用系统默认值 php.ini文件中uplo ...

  8. 3. HashMap和JSONObject用法

    <%@page import="net.sf.json.JSONObject"%><%@page import="java.util.List" ...

  9. JAVA Spring 事物 ( 已转账为例 ) 基于 XML 配置,事务类型说明

    < 1 > 配置文件 <?xml version="1.0" encoding="UTF-8"?> <beans xmlns=&q ...

  10. HTML5 Canvas ( 图片填充样式 ) fillStyle, createPattern

    <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title> ...