I’m testing out an interesting “threading” concept in PHP. Basically, I’m working to have a parent process spawn children that do stuff and return the results back to the parent via STDOUT in sort of a callback manner.
The way my example does it, the inner loop is too tight and burns 99% CPU:
while(true){
$ret = $thread->Listen();
if( $ret == 'DOINGSTUFF' ){
break;
}
}
I’d like to tone this while loop down to looping every 5 seconds using, for example, a sleep(). This brings CPU utilization to a much more rational level; however I’m concerned it will then “miss” some of the children “threads” returning results in case one child finishes during the parent’s sleeping process.
Can a PHP expert tell me whether this concern is well founded and if so, whether there’s anything I can do to cope?
Your example uses
proc_open, which isn’t exactly multi-threading. Anyway, when usingproc_open, the pipes streams will be available as long asproc_closeis not called, even if the process has actually terminated:Also, it is not necessary to use
sleep. Usually, you don’t want a script hanging for 5 seconds every pass doing nothing. Use usleep instead, which will also reduce the CPU usage but will still make the script responsive:The above will sleep for 50 micro-seconds, leaving CPU cycles to other running processes.
As for pure multi-threading, it is not possible in PHP. All you can do is fork a process. The difference with actual forking and the method you use (
proc_open) is that parent process data (variables, etc.) are forked to the child process as well. Forking should not be used in web applications, but only command-line programs, because web servers do not support it very well.