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
1 Answer
Reset to default 2Setting $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();
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744268836a4565998.html
评论列表(0条)