问题
How React PHP handles async non-blocking I/O ?
Nodejs uses its event queue which handles I/O on different threads. It uses libuv for this. As in PHP there isn't something like that, How React handles non-blocking I/O process on a single thread ?
回答1:
React PHP provides the primary event loop of the application; you are still required to write your code in a non-blocking way since it is all on one thread. The possible solutions to this all revolve around using php differently than I am sure most php developers are used to... Although React PHP provides the main loop; the bulk of the React PHP libraries are the implementations for sockets/streams/promise/etc. These have all employed methods to achieve non-blocking access to the I/O; typically through the use of stream_set_blocking
(http://php.net/manual/en/function.stream-set-blocking.php)
The other options include programming something similar to a FSM (https://en.wikipedia.org/wiki/Finite-state_machine); which allows it to continously update it's current state as it progresses; each time allowing for certain chunks of code to run, then giving up the thread to anything else in the loop. Essentially implementing your own time-slicing (https://en.wikipedia.org/wiki/Preemption_(computing)#Time_slice)
Another option is to implement threads (http://php.net/manual/en/book.pthreads.php) which is not enabled by default usually; And the last option I can think of is using process control to either fork/start/control other processes (http://php.net/manual/en/intro.pcntl.php) which is only enabled on *nix systems; which lets your host CPU control the time slicing; you will just be required to architect your application to either be thread safe, communicate with messaging queues, or some other mechanism.
tldr; Use your application architecture to not cause php to block, set your streams not to block, or use thread/process control to manage your own multi-threading.
来源:https://stackoverflow.com/questions/30863664/how-react-php-handles-async-non-blocking-i-o