SoFunction
Updated on 2025-03-09

Example of multi-process/multi-thread usage of php swoole [based on php7nts version]

This article describes the usage of php swoole multi-process/multi-threading. Share it for your reference, as follows:

Swoole's multi-threading is actually multi-process. The overhead of creating too many switching processes is very high. If you can use pthreads, it is recommended to use pthreads, because I am using the php7nts version and cannot use pthreads.

Swoole examples are as follows:

<?php
/**
  * Create multi-process
  */
$worker_num     = 6;    // Default number of processes$workers       = [];    // Process saving$redirect_stdout  = false;  // Redirect output; we will see the effect of this parameter usage.for($i = 0; $i < $worker_num; $i++){
  $process = new swoole_process('callback_function', $redirect_stdout);
  // Enable message queue int $msgkey = 0, int $mode = 2  $process->useQueue(0, 2);
  $pid = $process->start();
  // Pipeline write content  $process->write('index:'.$i);
  $process->push('Message Queue Contents of the Process');
  // Save the handle of each process  $workers[$pid] = $process;
}
/**
  * Subprocess callback
  * @param swoole_process $worker [description]
  * @return [type] [description]
  */
function callback_function(swoole_process $worker)
{
  $recv = $worker->pop();
  echo "Sub-output main content: {$recv}".PHP_EOL;
  //get guandao content
  $recv = $worker->read();
  $result = doTask();
  echo PHP_EOL.$result.'==='.$worker->pid.'==='.$recv;
  $worker->exit(0);
}
/**
  * Monitor/recycle child processes
  */
while(1){
  $ret = swoole_process::wait();
  if ($ret){// $ret is an array code is the process exit status code,    $pid = $ret['pid'];
    echo PHP_EOL."Worker Exit, PID=" . $pid . PHP_EOL;
  }else{
    break;
  }
}
/**
 * doTask
 * @return [type] [description]
 */
function doTask()
{
  sleep(2);
  return true;
}

For more information about PHP related content, please check out the topic of this site:Summary of PHP process and thread operation skills》、《Summary of PHP network programming skills》、《Introduction to PHP basic syntax》、《Complete collection of PHP array (Array) operation techniques》、《Summary of usage of php strings》、《PHP+mysql database operation tutorial"and"Summary of common database operation techniques for php

I hope this article will be helpful to everyone's PHP programming.