Skip to content

Instantly share code, notes, and snippets.

@rafinetiz
Last active December 1, 2020 09:47
Show Gist options
  • Save rafinetiz/3c6613cfef685232093cd5a0c13ac991 to your computer and use it in GitHub Desktop.
Save rafinetiz/3c6613cfef685232093cd5a0c13ac991 to your computer and use it in GitHub Desktop.
<?php
$test_data = [
'A' => 5,
'B' => 3,
'C' => 10,
'D' => 2
];
$child_process = [];
foreach ($test_data as $key => $time) {
$fork = pcntl_fork();
if ($fork == -1) {
echo 'Gagal membuat child process...' . PHP_EOL;
}
if ($fork > 0) {
echo sprintf("%s:\t %s -start -sleeps %d" . PHP_EOL, date('h:i:sa', time()), $key, $time);
$child_process[$fork] = $key; // masukan id child process kedalam array
} else {
// Code yang dijalankan didalam child process
sleep($time);
exit(0); // << penting supaya tidak terjadi zombie child
}
}
// Tunggu hingga semua child selesai
while(count($child_process) !== 0) {
foreach ($child_process as $process_id => $key) {
$waitstatus = pcntl_waitpid($process_id, $retcode, WNOHANG);
if ($waitstatus == -1 || $waitstatus > 0) {
// Child sudah selesai
echo sprintf("%s:\t %s -finish" . PHP_EOL, date('h:i:sa', time()), $child_process[$waitstatus]);
unset($child_process[$waitstatus]);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment