あなたのPHPプログラムに本当にマルチスレッド(PHPマルチスレッドクラス)を実現させます.

11038 ワード

WEBサーバでPHPマルチスレッド機能を実現.
もちろん、マルチスレッドについて深く理解している人は、WEBサーバを通じて実現されたマルチスレッドがマルチスレッドのいくつかの効果を模倣するしかないことを知っています.本当の意味でのマルチスレッドではありません.
しかし、いずれにしても、私たちのニーズを満たすことができます.マルチスレッドのような機能が必要な場合は、このクラスを採用することができます.
 
 1     /**   
 2      * @title:      PHP    (Thread)   
 3      * @version:    1.0   
 4      * @author:     phper.org.cn < [email protected] >   
 5      * @published:  2010-11-2   
 6      *    
 7      * PHP       :   
 8      *  require_once 'thread.class.php';   
 9      *  $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 . " " . 'Set in ' . Date('h:i:s', time()) . (double)microtime() . " ";   
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 ";    
57                         $out .= "Host: {$_SERVER['HTTP_HOST']} ";    
58                         $out .= "Connection: Close ";    
59                         fputs($fp,$out);    
60                         fclose($fp);    
61                     }    
62                 }    
63             }    
64         }    
65     }  

 
使用方法:
1     $thread = new thread();    
2     $thread->addthread('func1','info1');    
3     $thread->addthread('func2','info2');    
4     $thread->addthread('func3','info3');    
5     $thread->runthread();  

説明:
addthreadはスレッド関数を追加し、最初のパラメータは関数名であり、その後のパラメータ(オプション)は指定した関数に渡されるパラメータである.
runthreadはスレッドを実行する関数です.