Home > Article > Backend Development > How to understand PHP single thread
One of the characteristics of a single-threaded process is that it is executed sequentially. When encountering a time-consuming task, the unexecuted task will be in a waiting state. You must wait until the previous task is completed before executing it later. .
PHP is a typical single thread. It must be executed sequentially. If the previous one is not executed, the next one cannot be executed.
Of course, except swoole (Recommended learning: PHP video tutorial)
PHP From the beginning of its design to its popularity, there has been no obvious need to use multi-threading to solve it. needs. There are also corresponding solutions and alternatives where multi-threading is required. Multi-threading is not always better than single-threading. Multi-threading may introduce other problems (for example, a deadlock may occur when two threads call the same method in a class at the same time).
You can understand that PHP corresponding to a page request processing by a customer is processed by a single thread, so that you can edit/understand the business logic in the code from top to bottom, but PHP can Many threads are opened at the same time to handle the same PHP requested by many users, so PHP can also be regarded as "multi-threaded".
The execution of each PHP file is single-threaded, however, the server (apache/nigix/php-fpm) is multi-threaded. Every time a certain PHP file is accessed by the server, a new process/thread will be created to execute the corresponding PHP file.
That is to say, PHP is single-threaded for one request, but multiple requests are concurrent.
In fact, generally when writing PHP programs, it is considered to be single-threaded. The relationship between multiple requests is that sometimes reading and writing databases, files, sessions, etc. will be locked, which will cause subsequent requests to hang and wait for the previous request to complete before continuing.
As for coroutines, it can only be said to be a new program execution process (the old one is sequence, judgment, loop), and its essence is also single-threaded
So to be precise, PHP is Single-threaded can also be regarded as "multi-threaded" to a certain extent! ! !
The above is the detailed content of How to understand PHP single thread. For more information, please follow other related articles on the PHP Chinese website!