The following code works on my system. Note that I'm just a hobbyist, not an expert, so this might not fall under the category of 'best practices', and I have no idea what the security implications might be, but this absolutely works, creating multiple threads that all run concurrently. Never mind about the folder name 'Calories'. That just happens to be the folder I was working in when I threw together this example code.
main.php:
error_log('Hello, world, from main!');
$numberOfThreadsToCreate = 3;
for($i = 0; $i < $numberOfThreadsToCreate; ++$i) {
error_log("Main starting child {$i}");
$fp = fsockopen('localhost', 8888);
if(!$fp) {
error_log("$errstr ($errno)");
exit;
}
$firstSleep = $numberOfThreadsToCreate - $i;
$header = "GET /Calories/thread.php?threadID={$i}&firstSleep={$firstSleep}"
. " HTTP/1.1\r\n"
. "Host: localhost\r\n"
. "Connection: Close\r\n\r\n";
$r = fputs($fp, $header);
fclose($fp);
sleep(1);
}
for($i = 0; $i < 5; ++$i) {
sleep(1);
error_log('Main is still running');
}
error_log("Goodbye, cruel world, from main!");
thread.php
$myThreadID = $_GET['threadID'];
$sleep = $_GET['firstSleep'];
error_log("Hello, world, from child thread, ID={$myThreadID}!");
for($i = 0; $i < 5; ++$i) {
error_log("Child {$myThreadID} sleeping for {$sleep} seconds");
sleep($sleep);
$sleep = 1;
}
error_log("Goodbye, cruel world, from child thread, ID={$myThreadID}!");
And the logfile results:
Hello, world, from main!
Main starting child 0
Hello, world, from child thread, ID=0!
Child 0 sleeping for 3 seconds
Main starting child 1
Hello, world, from child thread, ID=1!
Child 1 sleeping for 2 seconds
Main starting child 2
Hello, world, from child thread, ID=2!
Child 2 sleeping for 1 seconds
Child 1 sleeping for 1 seconds
Child 2 sleeping for 1 seconds
Child 0 sleeping for 1 seconds
Child 1 sleeping for 1 seconds
Child 2 sleeping for 1 seconds
Child 0 sleeping for 1 seconds
Main is still running
Child 1 sleeping for 1 seconds
Child 2 sleeping for 1 seconds
Child 0 sleeping for 1 seconds
Main is still running
Child 1 sleeping for 1 seconds
Child 2 sleeping for 1 seconds
Child 0 sleeping for 1 seconds
Main is still running
Goodbye, cruel world, from child thread, ID=1!
Goodbye, cruel world, from child thread, ID=2!
Main is still running
Goodbye, cruel world, from child thread, ID=0!
Main is still running
Goodbye, cruel world, from main!