通过WEB服务器来实现PHP多线程功能。
当然,对多线程有深入理解的人都知道通过WEB服务器实现的多线程只能模仿多线程的一些效果,并不是真正意义上的多线程。
但不管怎么样,它还是能满足我们的一些需要的,在需要类似多线程的功能方面还是可以采用这个类。
01.
/**
02.
* @title: PHP多线程类(Thread)
03.
* @version: 1.0
04.
* @author: phper.org.cn < web@phper.org.cn >
05.
* @published: 2010-11-2
06.
*
07.
* PHP多线程应用示例:
08.
* require_once 'thread.class.php';
09.
* $thread = new thread();
10.
* $thread->addthread('action_log','a');
11.
* $thread->addthread('action_log','b');
12.
* $thread->addthread('action_log','c');
13.
* $thread->runthread();
14.
*
15.
* function action_log($info) {
16.
* $log = 'log/' . microtime() . '.log';
17.
* $txt = $info . "\r\n\r\n" . 'Set in ' . Date('h:i:s', time()) . (double)microtime() . "\r\n";
18.
* $fp = fopen($log, 'w');
19.
* fwrite($fp, $txt);
20.
* fclose($fp);
21.
* }
22.
*/
23.
class thread {
24.
25.
var $hooks = array();
26.
var $args = array();
27.
28.
function thread() {
29.
}
30.
31.
function addthread($func)
32.
{
33.
$args = array_slice(func_get_args(), 1);
34.
$this->hooks[] = $func;
35.
$this->args[] = $args;
36.
return true;
37.
}
38.
39.
function runthread()
40.
{
41.
if(isset($_GET['flag']))
42.
{
43.
$flag = intval($_GET['flag']);
44.
}
45.
if($flag || $flag === 0)
46.
{
47.
call_user_func_array($this->hooks[$flag], $this->args[$flag]);
48.
}
49.
else
50.
{
51.
for($i = 0, $size = count($this->hooks); $i < $size; $i++)
52.
{
53.
$fp=fsockopen($_SERVER['HTTP_HOST'],$_SERVER['SERVER_PORT']);
54.
if($fp)
55.
{
56.
$out = "GET {$_SERVER['PHP_SELF']}?flag=$i HTTP/1.1\r\n";
57.
$out .= "Host: {$_SERVER['HTTP_HOST']}\r\n";
58.
$out .= "Connection: Close\r\n\r\n";
59.
fputs($fp,$out);
60.
fclose($fp);
61.
}
62.
}
63.
}
64.
}
65.
}
使用方法:
$thread = new thread();
$thread->addthread('func1','info1');
$thread->addthread('func2','info2');
$thread->addthread('func3','info3');
$thread->runthread();
说明:
addthread是添加线程函数,第一个参数是函数名,之后的参数(可选)为传递给指定函数的参数。
runthread是执行线程的函数。
本文介绍了一种利用Web服务器实现PHP多线程的方法。尽管并非真正的多线程,但该方法能有效模拟多线程行为,适用于需要类似功能的应用场景。文章提供了具体的示例代码及使用说明。
1134

被折叠的 条评论
为什么被折叠?



