以下代码适用于我的系统。请注意,我只是一个业余爱好者,而不是专家,所以这可能不属于“最佳实践”的范畴,我不知道安全隐患可能是什么,但这绝对有效,创建多个运行的线程同时。不要介意文件夹名称“卡路里”。当我把这个示例代码放在一起时,这恰好是我正在工作的文件夹。
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}!");
日志文件结果:
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!