Home Backend Development PHP Tutorial PHP process pool and polling scheduling algorithm realize multi-tasking

PHP process pool and polling scheduling algorithm realize multi-tasking

Nov 13, 2019 pm 02:09 PM
php

phper Please understand the process scheduling strategy, CPU time slice, process control [creation, destruction, recycling, process signals] and process running flow and basic process groups, signal interruption principles, and the relationship between processes.

Communication of processes:

Anonymous pipes, named pipes, message queues, memory sharing, socketpair. Please test the code yourself

Process scheduling algorithm:

Polling, random distribution, scoreboard and other strategies, or basic algorithms such as a priority pole, a queue, or a stack [use it yourself]

Process pool:

If you have played with tcp, you should know that in order to be able to handle multiple clients, you have to use IO multiplexing technology [event multiplexer] or multiple Processes and multi-threads. Every time a client comes, a process or thread will be forked. In that case, the cost of context switching is very high, so we first create a group of processes [process pool], and when the client connects, it will be The algorithm [we use polling] is used to select a process to deliver tasks to do the work. This way, there is no need to go back and forth between creation and destruction, which improves its efficiency.

The following is the implementation of the PHP code version

<?php
/**
 * Created by PhpStorm.
 * User: 1655664358@qq.com
 * Date: 2019/1/12
 * Time: 16:18
 */
$flag = 1;
class process
{
    public $pid;
    public $name;
    public $file;
    public $num;
}
class instance
{
    public $processIdx;
    public $proc = [];
    public $processNum;
}
function sigHandler($sigNo)
{
    global $flag;
    $flag = 0;
    echo "信号中断处理".PHP_EOL;
}
function processPool(instance &$instance,$num)
{
    if (!$instance||$num==0){
        fprintf(STDERR,"%s","参数错误");
        return 1;
    }
    $instance->processIdx = 0;
    $instance->processNum = $num;
    pcntl_signal(SIGINT,&#39;sigHandler&#39;);
    pcntl_signal(SIGTERM,&#39;sigHandler&#39;);
    $process = new process();
    for ($i=1;$i<=$num;$i++){
        $instance->proc[$i] = clone $process;
        $instance->proc[$i]->file = $i;
        $instance->proc[$i]->pid = pcntl_fork();
        $instance->processIdx = $i;
        if ($instance->proc[$i]->pid<0){
            exit("进程创建失败");
        }
        else if ($instance->proc[$i]->pid>0){
            //nothing
            continue;
        }else{
            worker($instance);
        }
    }
    master($instance);
    $exitProcess= [];
    while (1){
        for ($i=1;$i<=$num;$i++){
        //非阻塞方式回收子进程
            pcntl_waitpid($instance->proc[$i]->pid,$status,WNOHANG);
            if ($status){
                $exitProcess[] = $instance->proc[$i]->pid;
                fwrite(STDOUT,"worker#".$instance->proc[$i]->pid."-".$status,30);
            }
        }
        if (count($exitProcess)==$instance->processNum){
            exit(0);
        }
        usleep(1000);
    }
}
//简单的轮询算法  自己可以用队列,随机,链表,栈链,二叉树啥的折腾
function roundRobin(&$instance,$roll)
{
    /** @var instance $instance */
    return $instance->proc[$roll%$instance->processNum+1];
}
function master(&$instance)
{
    /** @var instance $instance */
    fprintf(STDOUT,"master 进程 %d\n",$instance->processIdx);
    global $flag;
    $roll = 0;
    while ($flag){
        pcntl_signal_dispatch();
        /** @var process $process */
        $process = roundRobin($instance,$roll++);
        echo "轮询的进程:".$process->pid.PHP_EOL;
        $file = $process->file;
        posix_mkfifo($file,0666);
        $fd = fopen($file,"w");
        fwrite($fd,"hi",2);
        sleep(1);
    }
    for ($i=1;$i<=$instance->processNum;$i++){
        posix_kill($instance->proc[$i]->pid,9);
    }
    fprintf(STDOUT,"master shutdown %d\n",$instance->processIdx);
}
function getProcess(&$instance)
{
    /** @var instance $instance */
    return $instance->proc[$instance->processIdx];
}
function worker(&$instance)
{
    /** @var process $process */
    $process = getProcess($instance);
    while (1){
        $file = $process->file;
        posix_mkfifo($file,0666);
        $fd = fopen($file,"r");
        $content = fread($fd,10);
        fprintf(STDOUT,"worker#%d读取的内容:%s file=%d\n",posix_getpid(),$content,$file);
    }
    exit(0);
}
$instance = new instance();
processPool($instance,5);
Copy after login

Effect

PHP process pool and polling scheduling algorithm realize multi-tasking

The above is the detailed content of PHP process pool and polling scheduling algorithm realize multi-tasking. For more information, please follow other related articles on the PHP Chinese website!

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

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)

CakePHP Project Configuration CakePHP Project Configuration Sep 10, 2024 pm 05:25 PM

In this chapter, we will understand the Environment Variables, General Configuration, Database Configuration and Email Configuration in CakePHP.

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

CakePHP Date and Time CakePHP Date and Time Sep 10, 2024 pm 05:27 PM

To work with date and time in cakephp4, we are going to make use of the available FrozenTime class.

CakePHP File upload CakePHP File upload Sep 10, 2024 pm 05:27 PM

To work on file upload we are going to use the form helper. Here, is an example for file upload.

CakePHP Routing CakePHP Routing Sep 10, 2024 pm 05:25 PM

In this chapter, we are going to learn the following topics related to routing ?

Discuss CakePHP Discuss CakePHP Sep 10, 2024 pm 05:28 PM

CakePHP is an open-source framework for PHP. It is intended to make developing, deploying and maintaining applications much easier. CakePHP is based on a MVC-like architecture that is both powerful and easy to grasp. Models, Views, and Controllers gu

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

CakePHP Creating Validators CakePHP Creating Validators Sep 10, 2024 pm 05:26 PM

Validator can be created by adding the following two lines in the controller.

See all articles