Multiprocessing using built-in fork functions

suggest change

You can use built-in functions to run PHP processes as forks. This is the most simple way to achieve parallel work if you don’t need your threads to talk to each other.

This allows you to put time intensive tasks (like uploading a file to another server or sending an email) to another thread so your script loads faster and can use multiple cores but be aware that this is not real multithreading and your main thread won’t know what the children are up to.

Note that under Windows this will make another command prompt pop up for each fork you start.

master.php

$cmd = "php worker.php 10";
if(strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') // for windows use popen and pclose
{
    pclose(popen($cmd,"r"));
}
else //for unix systems use shell exec with "&" in the end
{
    exec('bash -c "exec nohup setsid '.$cmd.' > /dev/null 2>&1 &"');
}

worker.php

//send emails, upload files, analyze logs, etc
$sleeptime = $argv[1];
sleep($sleeptime);

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents