search
Homephp教程php手册php 实现多线程,php多线程

php 实现多线程,php多线程

Jun 13, 2016 am 09:19 AM
phpsocketnot supportaccomplishWayyesofprogramthreadpass

php 实现多线程,php多线程

通过php的Socket方式实现php程序的多线程。php本身是不支持多线程的,那么如何在php中实现多线程呢?可以想一下,WEB服务器本身都是支持多线程的。每一个访问者,当访问WEB页面的时候,都将调用新的线程,通过这一点我们可以利用WEB服务器自身的线程来解决PHP不支持多线程的问题。
 
  下面给出通过 fsockopen() 建立socket连接,然后用 用fputs() 发送消息,来实现的PHP多线程类代码:
$fp=fsockopen($_SERVER['HTTP_HOST'],80,&$errno,&$errstr,5); 
if(!$fp){
echo "$errstr ($errno)
\n";
}
fputs($fp,"GET $_SERVER[PHP_SELF]?flag=1\r\n"); 
fclose($fp);



 上面这段代码只是一个线程的操作过程。多进行几个这样的操作就是多线程了。目前所谓PHP的多线程程序都是基于这个方式的。

下面给一个完整的线程类代码。
/** 
@title:PHP多线程类(Thread) 
@version:1.0 
@author:axgle  
*/ 
class thread { 
var $count; 
function thread($count=1) { 

$this->count=$count; 


function _submit() { 
for($i=1;$icount;$i++) $this->_thread(); 
return true; 



function _thread() { 
$fp=fsockopen($_SERVER['HTTP_HOST'],80,&$errno,&$errstr,5); 

if(!$fp){
echo "$errstr ($errno)
\n";
}
fputs($fp,"GET $_SERVER[PHP_SELF]?flag=1\r\n"); 
fclose($fp); 


function exec($func) { 
isset($_GET['flag'])?call_user_func($func):$this->_submit(); 





//应用例子:
$th=new thread(10);//10个线程 
$th->exec('demo');//执行行自定义的函数 

function demo() { 
fopen('data/'.microtime(),'w'); 


?>

http://codechina.spaces.live.com/blog/cns!bca6db10a924c24!575.entry

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.