進程的通訊:
匿名管道,命名管道,訊息佇列,記憶體共用,socketpair 請自行擼程式碼測試哦
進程的排程演算法:
輪詢,隨機分發,計分板等策略或是搞個優先極或是佇列,或是堆疊等基本的演算法【自己去發揮哦】
進程池:
擼過 tcp 的話應該知道要能處理多個用戶端,就得用 IO 復用技術【事件多路分發器】或是多進程以及多執行緒,每來一個用戶端就 fork 一個進程或是執行緒,那樣的話上下文切換成本特別高,所以咱們先建立好一組進程【進程池】,等用戶端連線上來的時候,通過某種演算法【我們用的輪詢】來選擇某個進程投遞任務來幹活,這樣的話就不用建立又銷毀來回折騰了,提升它的效率。
下面是 PHP 程式碼版本的實現
<?php /** * Created by PhpStorm. * User: [email protected] * 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,'sigHandler'); pcntl_signal(SIGTERM,'sigHandler'); $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 進程 %dn",$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 %dn",$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=%dn",posix_getpid(),$content,$file); } exit(0); } $instance = new instance(); processPool($instance,5);
效果
以上就是PHP 進程池與輪詢排程演算法實現多工的詳細內容,更多請關注TW511.COM其它相關文章!