Home php教程 php手册 php实现多线程

php实现多线程

Jun 13, 2016 am 11:23 AM
php send Multiple accomplish server thread want ask process

php实现多线程
服务器发送多个请求要实现多进程要方便很多。只能使用在cli模式。可以用在特殊场合,如邮件发送任务等。
资源的共享访问使用了文件锁,并不是很可靠,主要是为了能够在Windwos下使用,如果确实有必要可以考虑自己改用相应的信号灯机制(这个扩展只能用于xUNIX)。

实例
[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             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]

进程管理类
[php]
/**
* @copyright 2007 movivi
* @author  徐智 
*
* $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', '');
/*****************************************************************************/
/* 初始化 */
define('CMD_MAIN_PROCESS_KEY', 'main_process_key');
define('CMD_CHILD_PROCESS_NAME', 'child_process_name');
define('CMD_CHILD_PROCESS_PARAM', 'child_process_param');

function init_my_process() {
    $GLOBALS['gal_obj_cmd'] = new my_cmd_argv();
    $key = $GLOBALS['gal_obj_cmd']->get_value(CMD_MAIN_PROCESS_KEY);
    $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多进程类
*
* 你需要从这个对象继承,然后实现你自己的run处理
*/
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 $cmd_argv = array();
    public function __construct() {
        $argv = $_SERVER['argv'];
        for ($i = 1; $i             $cmd = explode('=', $argv[$i]);
            $this->cmd_argv[$cmd[0]] = isset($cmd[1]) ? $cmd[1] : '';
        }
    }

    public function get_key($key) {
        return isset($this->cmd_argv[$key]);
    }

    public function get_value($key) {
        return isset($this->cmd_argv[$key]) ? $this->cmd_argv[$key] : false;
    }
}

/**
* php多进程管理类
* 可以在PHP中实现多进程处理,只限在控制台方式使用
* 当前的信号实现机制采用文件方式
*
*/
class my_process_m {
    /**
     * @var array $task_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(CMD_CHILD_PROCESS_NAME);
        $param = $GLOBALS['gal_obj_cmd']->get_value(CMD_CHILD_PROCESS_PARAM);
        $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();
    }

    /**
     * 停止所有进程
     *
     */
    public function stop_all() {
    }

    /**
     * 是否是主进程
     *
     */
    public function is_main() {
        return $this->is_main;
    }

    /**
     * 是不是已经存在一个活动信号
     *
     * @param   string      $key
     * @return  bool       
     */
    public function exist($key) {
        return file_exists($this->build_lock_id($key));
    }

    /**
     * 获取一个信号
     *
     * @param   string      $key    
     * @param   int         $max_acquire    最大请求阻塞数量
     * @return mix 如果成功返回一个信号ID
     *
     */
    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;
    }

    /**
     * 释放一个信号
     *
     * @param   string      $key    
     * @return  bool        如果成功返回一个信号true
     *
     */
    public function remove($key) {
        return $this->release_lock($key);
    }

    /**
     * 获取一个信号
     *
     * @param string    $id         信号ID
     * @param bool      $block      是否阻塞
     */
    public function acquire($id, $block=false) {
        if ($block) {
            return flock($id, LOCK_EX);
        } else {
            return flock($id, LOCK_EX + LOCK_NB);
        }
    }

    /**
     * 释放一个信号
     *
     */
    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 . ' '
            . CMD_CHILD_PROCESS_PARAM . '="' . base64_encode(serialize($param)) . '" '
            . CMD_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++ 0);
        } else {
            $this->run_child_process();
        }
    }

    public function set_max_run($max=1000) {
        $this->max_run = $max;
    }
}


Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

See all articles