admin管理员组

文章数量:1401176

I am trying to understand how to create a multi-process inside a loop in Workerman. And is it even possible to achieve this?

The goal is to have multiple processes run in parallel to iterate through an array. Can anyone help me with this?

Thank you for your assistance.

$worker = new \Workerman\Worker;

$worker->onWorkerStart = function () {
     foreach($array as $item) {
         $worker->count = 10;
         // DO SOME STUFF 
     }
}

I am trying to understand how to create a multi-process inside a loop in Workerman. And is it even possible to achieve this?

The goal is to have multiple processes run in parallel to iterate through an array. Can anyone help me with this?

Thank you for your assistance.

$worker = new \Workerman\Worker;

$worker->onWorkerStart = function () {
     foreach($array as $item) {
         $worker->count = 10;
         // DO SOME STUFF 
     }
}
Share Improve this question edited Mar 24 at 7:05 rozsazoltan 11k6 gold badges20 silver badges57 bronze badges asked Mar 23 at 21:23 Евгений АнтиповЕвгений Антипов 5602 gold badges6 silver badges20 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 2

Setting $worker->count inside the loop won’t create new processes dynamically.

You need something similar to this.

$worker = new \Workerman\Worker();
$worker->count = 10; # Define here
$array = [...]; # data

$worker->onWorkerStart = function($worker) use ($array) {
 
    $totalItems = count($array);
    $perWorker = ceil($totalItems / $worker->count);
    $workerId = $worker->id; # worker unique id
    $start = $workerId * $perWorker;
    $slice = array_slice($array, $start, $perWorker);
    
    foreach ($slice as $item) {
        # Process each item
    }
};

\Workerman\Worker::runAll();

本文标签: workerPHP Workerman Multiple processes in foreach loopStack Overflow