实现php多线程类的案例

黄舟
黄舟 原创
2023-03-17 11:22:02 1962浏览

我们在之前给大家介绍了php多线程的实现方法,以及异步调用,都知道通过WEB服务器实现的多线程只能模仿多线程的一些效果,并不是真正意义上的多线程.但不管怎么样,它还是能满足我们的一些需要的,那么今天我们就实现php多线程的类!

php多线程类:

/** 
* @title: PHP多线程类(Thread) 
* @version: 1.0 
* 
* PHP多线程应用示例: 
* require_once 'thread.class.php'; 
* $thread = new thread(); 
* $thread->addthread('action_log','a'); 
* $thread->addthread('action_log','b'); 
* $thread->addthread('action_log','c'); 
* $thread->runthread(); 
* 
* function action_log($info) { 
* $log = 'log/' . microtime() . '.log'; 
* $txt = $info . "rnrn" . 'Set in ' . Date('h:i:s', time()) . (double)microtime() . "rn"; 
* $fp = fopen($log, 'w'); 
* fwrite($fp, $txt); 
* fclose($fp); 
* } 
*/ 
class thread { 
var $hooks = array(); 
var $args = array(); 
function thread() { 
} 
function addthread($func) 
{ 
$args = array_slice(func_get_args(), 1); 
$this->hooks[] = $func; 
$this->args[] = $args; 
return true; 
} 
function runthread() 
{ 
if(isset($_GET['flag'])) 
{ 
$flag = intval($_GET['flag']); 
} 
if($flag || $flag === 0) 
{ 
call_user_func_array($this->hooks[$flag], $this->args[$flag]); 
} 
else 
{ 
for($i = 0, $size = count($this->hooks); $i < $size; $i++) 
{ 
$fp=fsockopen($_SERVER['HTTP_HOST'],$_SERVER['SERVER_PORT']); 
if($fp) 
{ 
$out = "GET {$_SERVER['PHP_SELF']}?flag=$i HTTP/1.1rn"; 
$out .= "Host: {$_SERVER['HTTP_HOST']}rn"; 
$out .= "Connection: Closernrn"; 
fputs($fp,$out); 
fclose($fp); 
} 
} 
} 
} 
}

使用方法,代码如下:

$thread = new thread(); 
$thread->addthread('func1','info1'); 
$thread->addthread('func2','info2'); 
$thread->addthread('func3','info3'); 
$thread->runthread();

说明:

addthread() 是添加线程函数,第一个参数是函数名,之后的参数(可选)为传递给指定函数的参数.

runthread() 是执行线程的函数.

总结:

本文给大家分享了一个php多线程的类,以后就不需要在去写那么多代码,下次需要的时候就可以直接调用了,希望可以对你有所帮助!

相关推荐:

php实现异步调用多线程的方法


php多线程模拟实现的三种方法介绍


php多线程的实现实例


php多线程一种实现方法—shell

以上就是实现php多线程类的案例的详细内容,更多请关注php中文网其它相关文章!

声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn核实处理。