Heim  >  Artikel  >  Backend-Entwicklung  >  PHP实现多进程并行操作(可做守护进程)

PHP实现多进程并行操作(可做守护进程)

WBOY
WBOYOriginal
2016-07-25 09:01:30857Durchsuche
PHP简单实现多进程并行处理,子进程负责处理事物,父进程可控制子进程数量,用pcntl扩展实现(备注:在windows下此效果无法实现)                               
                   
                               
                                               
                                       
            
  1. /**
  2. * 入口函数
  3. * 将此文件保存为 ProcessOpera.php
  4. * 在terminal中运行 /usr/local/php/bin/php ProcessOpera.php &
  5. * 查看进程 ps aux|grep php
  6. */
  7. ProcessOpera("runCode", array(), 8);
  8. /**
  9. * run Code
  10. */
  11. function runCode($opt = array()) {
  12.    //需要在守护进程中运行的代码
  13. }
  14. /**
  15. * $func为子进程执行具体事物的函数名称
  16. * $opt为$func的参数 数组形式
  17. * $pNum 为fork的子进程数量
  18. */
  19. function ProcessOpera($func, $opts = array(), $pNum = 1) {
  20.     while(true) {
  21.         $pid = pcntl_fork();
  22.         if($pid == -1) {
  23.             exit("pid fork error");
  24.         }   
  25.         if($pid) {
  26.             static $execute = 0;
  27.             $execute++;
  28.             if($execute >= $pNum) {
  29.                 pcntl_wait($status);
  30.                 $execute--;
  31.             }   
  32.         } else {
  33.             while(true) {
  34.                 //somecode
  35.                 $func($opts);
  36.                 sleep(1);
  37.             }   
  38.             exit(0);
  39.         }   
  40.     }   
  41. }
复制代码


Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn