php進程間通訊實例分析
來源:易賢網(wǎng) 閱讀:1611 次 日期:2016-08-16 14:24:49
溫馨提示:易賢網(wǎng)小編為您整理了“php進程間通訊實例分析”,方便廣大網(wǎng)友查閱!

本文實例講述了php進程間通訊的方法。分享給大家供大家參考,具體如下:

php單進程單線程處理批量任務太慢了,受不鳥了,但是php不能多線程,最終選擇了多進程處理批量任務.

php多進程主要使用for進行分裂,然后利用的unix/linux的信號量進行進程間通訊.

本例使用的是:生產(chǎn)者=>消費者=>收集器,的模式.

<?php

// ===== 全局變量 =====

// ipc進程間通訊

$key = ftok(__FILE__, "a");

$queue = msg_get_queue($key);

// 進程ID

$producer_pid = 0;

$consumers_pid = array();

$collector_pid = posix_getpid();

// ===== 消費者 =====

for ($i=0; $i < 2; $i++) {

  $consumer_pid = pcntl_fork();

  if ($consumer_pid == -1) {

    exit("could not fork!\n");

  } else if ($consumer_pid) {

    // pcntl_wait($status);

    echo "consumer_pid: $consumer_pid\n";

    $consumers_pid[] = $consumer_pid;

  } else {

    $pid = posix_getpid();

    echo "consumer_pid: $pid start\n";

    while (true) {

      msg_receive($queue, $pid, $msgtype, 1024, $message);

      if ($message == "exit") {

        break;

      }

      // 數(shù)據(jù)處理

      $n = intval($message);

      msg_send($queue, $collector_pid, $n * $n);

    }

    exit("consumer ok!\n");

  }

}

// ===== 產(chǎn)生者 =====

$producer_pid = pcntl_fork();

if ($producer_pid == -1) {

  exit("could not fork!\n");

} else if ($producer_pid) {

  // pcntl_wait($status);

  echo "producer_pid: $producer_pid\n";

} else {

  $pid = posix_getpid();

  echo "producer_pid: $pid start\n";

  $n = 0;

  for ($i=0; $i < 10; $i++) {

    foreach ($consumers_pid as $consumer_pid) {

      $n++;

      msg_send($queue, $consumer_pid, $n);

    }

    sleep(1);

  }

  foreach ($consumers_pid as $consumer_pid) {

    msg_send($queue, $consumer_pid, "exit");

  }

  sleep(1);

  msg_send($queue, $collector_pid, "exit");

  exit("producer ok!\n");

}

// ===== 收集器 =====

while (true) {

  msg_receive($queue, $collector_pid, $msgtype, 1024, $message);

  if ($message == "exit") {

    break;

  }

  echo sprintf("% 5d: %d\n", $msgtype, $message);

}

exit("collector ok!\n");

希望本文所述對大家PHP程序設(shè)計有所幫助。

更多信息請查看網(wǎng)絡編程
易賢網(wǎng)手機網(wǎng)站地址:php進程間通訊實例分析
關(guān)于我們 | 聯(lián)系我們 | 人才招聘 | 網(wǎng)站聲明 | 網(wǎng)站幫助 | 非正式的簡要咨詢 | 簡要咨詢須知 | 加入群交流 | 手機站點 | 投訴建議
工業(yè)和信息化部備案號:滇ICP備2023014141號-1 云南省教育廳備案號:云教ICP備0901021 滇公網(wǎng)安備53010202001879號 人力資源服務許可證:(云)人服證字(2023)第0102001523號
聯(lián)系電話:0871-65317125(9:00—18:00) 獲取招聘考試信息及咨詢關(guān)注公眾號:hfpxwx
咨詢QQ:526150442(9:00—18:00)版權(quán)所有:易賢網(wǎng)