当然,对多线程有深入理解的人都知道通过web服务器实现的多线程只能模仿多线程的一些效果,并不是真正意义上的多线程。
但不管怎么样,它还是能满足我们的一些需要的,在需要类似多线程的功能方面还是可以采用这个类。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
/**
*
* 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 . \r\n\r\n . 'set in ' . date('h:i:s', time()) . (double)microtime() . \r\n;
* $fp = fopen($log, 'w');
* fwrite($fp, $txt);
* fclose($fp);
* }
*/
class thread {
var$hooks = array();
var$args = array();
functionthread() {
}
functionaddthread($func)
{
$args= array_slice(func_get_args(), 1);
$this->hooks[] =$func;
$this->args[] =$args;
returntrue;
}
functionrunthread()
{
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.1\r\n;
$out.= host: {$_server['http_host']}\r\n;
$out.= connection: close\r\n\r\n;
fputs($fp,$out);
fclose($fp);
}
}
}
}
}
