Home  >  Article  >  Backend Development  >  PHP+shell实现多线程的方法_php技巧

PHP+shell实现多线程的方法_php技巧

WBOY
WBOYOriginal
2016-05-16 20:12:341744browse

本文实例讲述了PHP+shell实现多线程的方法。分享给大家供大家参考。具体如下:

这里介绍如何借助shell脚本实现多线程。

先写个简单的php代码,这里为了让脚本执行时间更长,方便看效果,sleep一下,呵呵!先看下test.php的代码:

PHP代码:

<&#63;php
for ($i=0;$i<10;$i++) {
  echo $i;
  sleep(10);
}
&#63;>

在看下shell脚本的代码,非常简单

#!/bin/bash
for i in 1 2 3 4 5 6 7 8 9 10
do 
  /usr/bin/php -q /var/www/html/test.php &
done 

注意到在请求php代码的那行有一个&符号吗,这个是关键,不加的话是不能进行多线程的,&表示讲服务推送到后台执行,因此,在 shell的每次的循环中不必等php的代码全部执行完在请求下一个文件,而是同时进行的,这样就实现了多线程,下面运行下shell看下效果,这里你将 看到10个test.php进程再跑,再利用linux的定时器,定时请求这个shell,在处理一些需要多线程的任务,例如,批量下载时,非常好用!

希望本文所述对大家的php程序设计有所帮助。

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn