私は文字列を並列に分割して処理する必要があるタスクを達成しようとしています。pcntl_fork()を使用して並列に処理する配列
私はサイズ100
の複数の配列にそれを打破する必要があるサイズ3000のアレイ、私が使用して達成した:
$chunks = array_chunk($keywords,100); // $keywords is my array of size 3000
を今はprocess
場所と呼ばれるメソッドを持っているが私は各チャンク(サイズ100の小さい配列)を処理する必要があります。
public function process($chunk){
foreach($chunk as $keyword){
// Process the single keyword...
}
}
しかし、上記のタスクは、すべてのチャンクが並列に処理されるような方法で達成しようとする... 私の全体のスクリプトは次のとおりです。私は3000を持っている場合
<?php
public function readKeywords(){
$keywords = array();
// code to read a file and populate the array $keywords
return $keywords;
}
public function process($chunk){
foreach($chunk as $keyword){
// Process the single keyword...
}
}
public function init($chunks,$index = 0){
$pid = pcntl_fork();
if($pid === -1){
// Couldn't fork
} else if($pid){
process($chunks[$index]);
}else{
$index++;
if(count($chunks) > $index){
process($chunks,$index);
}
}
}
public function start($keywords){
$chunks = array_chunk($keywords,100);
init($chunks);
}
$keywords = readKeywords();
start($keywords);
?>
今の課題は、ありますキーワードを配列に入れて、それを100の塊で分割すると、各塊を処理するための30のアクティブなプロセスがあります。
3
プロセスがアクティブな場合は、pause
チャンクを作成する必要があります。 3
プロセスのいずれかが完了すると、再帰が再度発生し、新しい子プロセスを作成し、次のチャンクを処理する必要があります。これにより実行時間は長くなりますが、問題ありません。
だからプロセスの数を制限するために、私は次のコードを試みたが、運を持つ:
public void init($chunks){
$pids = array();
for($i = 0;$i < 3;$i++){
$pid = pcntl_fork();
if($pid === -1){
// Couldn't fork
} else if($pid){
process($chunks[$i]);
}else{
exit();
}
}
for($i = 0;$i < count($pids);$i++){
pcntl_waitpid($pids[$i],$status,WUNTRACED); // Read somewhere that it waits till it's child process has completed execution
}
if($index < count($chunks)) // If there are chunks remaining to be processed {
$newChunks = array();
for($i = 3;$i < count($chunks);$i++){
$newChunks[] = $chunks[$i];
}
init($newChunks);
}
}
は、多くのワークアウト、ない幸運されています。助けてください。
番号を実行しているどのように多くのそれらのチェックする
$processes
をカウントし、その後、exec('ps -C '.$filename, $processes);
のようなものを試してみてください。コードを介してそれを行う必要があります。他の解決策? –