Multithreading in php

Source: Internet
Author: User
Tags bool flock md5 sleep

Multithreading in php
It is much easier for the server to send multiple requests to implement multiple processes. It can only be used in cli mode. It can be used in special cases, such as sending tasks.
The file lock is not very reliable for shared access to resources, mainly for use in Windwos, if necessary, consider switching to the corresponding traffic signal mechanism (this extension can only be used for xUNIX ).

Instance
[Php]
Define ('dir _ PHP_EXEC ', 'php ');
Define ('dir _ MAIN_EXEC ', _ FILE __);
Define ('dir _ TMP ','/tmp ');
Require_once ('My _ process. Php ');

Class pp extends my_process_base {
Public function run ($ param = null ){
For ($ I = 0; $ I <4; $ I ++ ){
Echo "111 $ paramn ";
Sleep (1 );
        }
    }
}

Init_my_process ();
$ Obj = $ GLOBALS ['Gal _ obj_process_m '];
If ($ obj-> is_main ()){
$ Obj-> run_task ('pp ', 'A ');
$ Obj-> run_task ('pp ',' B ');
$ Obj-> run_task ('pp ', 'C ');
$ Obj-> run_task ('pp ', 'D ');
// $ Obj-> run_task ('pp ',' B ');
$ Obj-> set_max_run (10 );
$ Obj-> run ();
}

[/Php]

Process Management
[Php]
/**
* @ Copyright 2007 movivi
* @ Author Xu Zhi <xzfred@gmail.com>
*
* $ Id: getPage. php 11 2007-09-21 02: 15: 01Z fred $
*/
If (! Defined ('dir _ PHP_EXEC ') define ('dir _ PHP_EXEC', 'php ');
// If (! Defined ('dir _ MAIN_EXEC ') define ('dir _ MAIN_EXEC ','');
If (! Defined ('dir _ TMP ') define ('dir _ TMP ','');
/*************************************** **************************************/
/* Initialize */
Define ('command _ MAIN_PROCESS_KEY ', 'Main _ process_key ');
Define ('command _ CHILD_PROCESS_NAME ', 'Child _ process_name ');
Define ('command _ CHILD_PROCESS_PARAM ', 'Child _ process_param ');

Function init_my_process (){
$ GLOBALS ['Gal _ obj_cmd '] = new my_1__argv ();
$ Key = $ GLOBALS ['Gal _ obj_cmd ']-> get_value (pai_main_process_key );
$ Key = false? '': $ Key;
$ GLOBALS ['Gal _ obj_process_m '] = new my_process_m ($ key );
If (! $ GLOBALS ['Gal _ obj_process_m ']-> is_main () $ GLOBALS ['Gal _ obj_process_m']-> run ();
}

/**
* Php multi-process
*
* You need to inherit from this object and then implement your own run processing.
*/
Abstract class my_process_base {
Public function _ construct ($ auto_run = true, $ name = ''){
    }

Public function _ destruct (){
Echo "@ endn ";
    }

Abstract public function run ($ param = null );
}


Class my_cmd_argv {
Private $ pai_argv = array ();
Public function _ construct (){
$ Argv = $ _ SERVER ['argv'];
For ($ I = 1; $ I <count ($ argv); $ I ++ ){
$ Cmd = explode ('=', $ argv [$ I]);
$ This-> cmd_argv [$ cmd [0] = isset ($ cmd [1])? $ Cmd [1]: '';
        }
    }

Public function get_key ($ key ){
Return isset ($ this-> pai_argv [$ key]);
    }

Public function get_value ($ key ){
Return isset ($ this-> 1__argv [$ key])? $ This-> pai_argv [$ key]: false;
    }
}

/**
* Php multi-process management
* Multi-process processing can be implemented in PHP, which is only available on the console.
* The current signal implementation mechanism adopts the file mode
*
*/
Class my_process_m {
/**
* @ Var array $ task_list
* Process List
*/
Private $ task_list = array ();
Private $ lock_list = array ();
Private $ lock = null;
Private $ is_main = false;
Private $ max_run= 3600000;

Private function release_lock ($ key = null ){
$ Lock = & $ this-> lock_list;
If (! Is_null ($ key )){
$ Key = md5 ($ this-> build_lock_id ($ key ));
If (isset ($ lock [$ key]) {
If (is_resource ($ lock [$ key] [0]) fclose ($ lock [$ key] [0]);
Unlink ($ lock [$ key] [1]);
Unset ($ lock [$ key]);
            }
Return true;
        }

Foreach ($ lock as $ k => $ h ){
If (is_resource ($ h) fclose ($ h );
Unset ($ lock [$ k]);
        }
Return true;
    }

Private function release_task ($ key = null ){
$ Task = & $ this-> task_list;
If (! Is_null ($ key) & isset ($ task [$ key]) {
If (is_resource ($ task [$ key]) pclose ($ task [$ key]);
Unset ($ task [$ key]);
} Else {
Foreach ($ task as $ k => $ h ){
If (is_resource ($ h) pclose ($ h );
Unset ($ task [$ k]);
            }
        }
Return true;
    }
           
Private function build_lock_id ($ key ){
Return DIR_TMP. DIRECTORY_SEPARATOR. $ key. '_ sem. Lock ';
    }

Protected function run_child_process (){
$ Class = $ GLOBALS ['Gal _ obj_cmd ']-> get_value (pai_child_process_name );
$ Param = $ GLOBALS ['Gal _ obj_cmd ']-> get_value (pai_child_process_param );
$ Param = ''? Null: unserialize (base64_decode (trim ($ param )));
$ Obj = new $ class ();
$ Obj-> run ($ param );
$ This-> task_list [] = $ obj;
    }

Public function _ construct ($ lock = ''){
If ($ lock = ''){
$ This-> is_main = true;
$ Key = md5 (uniqid (). '_ main. my_process ';
$ Lock = array ($ key, $ this-> get ($ key ));
} Else {
$ This-> is_main = false;
$ Lock = array ($ lock, 0 );
        }
$ This-> lock = $ lock;
    }

Public function _ destruct (){
$ This-> release_lock ();
$ This-> release_task ();
    }

/**
* Stop all processes
     *
*/
Public function stop_all (){
    }

/**
* Whether it is the main process
     *
*/
Public function is_main (){
Return $ this-> is_main;
    }

/**
* Is there an activity signal?
     *
* @ Param string $ key
* @ Return bool
*/
Public function exist ($ key ){
Return file_exists ($ this-> build_lock_id ($ key ));
    }

/**
* Obtain a signal.
     *
* @ Param string $ key
* @ Param int $ max_acquire maximum number of request blocking
* @ Return mix if a signal ID is returned successfully
     *
*/
Public function get ($ key, $ max_acquire = 5 ){
$ Fn = $ this-> build_lock_id ($ key );
If (isset ($ this-> lock_list [md5 ($ fn)]) return false;
$ Id = fopen ($ fn, 'A + ');
If ($ id) $ this-> lock_list [md5 ($ fn)] = array ($ id, $ fn );
Return $ id;
    }

/**
* Release a signal
     *
* @ Param string $ key
* @ Return bool returns a true signal if it is successful.
     *
*/
Public function remove ($ key ){
Return $ this-> release_lock ($ key );
    }

/**
* Obtain a signal.
     *
* @ Param string $ id signal ID
* @ Param bool $ block blocking
*/
Public function acquire ($ id, $ block = false ){
If ($ block ){
Return flock ($ id, LOCK_EX );
} Else {
Return flock ($ id, LOCK_EX + LOCK_NB );
        }
    }

/**
* Release a signal
     *
*/
Public function release ($ id ){
Flock ($ id, LOCK_UN );
    }
Public function run_task ($ process_name, $ param = null ){
$ This-> task_list [] = popen (DIR_PHP_EXEC. '-f'. DIR_MAIN_EXEC .'--'
. CMD_CHILD_PROCESS_NAME. '='. $ process_name .''
. Pai_child_process_param. '= "'. base64_encode (serialize ($ param )).'"'
. Pai_main_process_key. '= "'. $ this-> lock [0]. '"',
'R ');
    }

Public function run ($ auto_run = true ){
If ($ this-> is_main ){
$ Ps = & $ this-> task_list;
$ Max_run = & $ this-> max_run;
$ Id = 0;
Do {
// Echo "process ------------------------------------------: n ";
$ C = 0;
Foreach ($ ps as $ k => $ h ){
$ C ++;
$ Msg = fread ($ h, 8000 );
If (substr ($ msg,-5, 4) ===' @ end '){
Echo "end process: [$ k] [$ id] echo n {$ msg} n ";
$ This-> release_task ($ k );
} Else {
Echo "process: [$ k] [$ id] echo n {$ msg} n ";
                    }
                }
Sleep (1 );
} While ($ auto_run & $ id ++ <$ max_run & $ c> 0 );
} Else {
$ This-> run_child_process ();
        }
    }

Public function set_max_run ($ max = 1000 ){
$ This-> max_run = $ max;
    }
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.