PHP does not support multi-threading by default. To use multi-threading, you need to install the pthread extension. To install the pthread extension, you must use the --enable-maintainer-zts parameter to recompile PHP. This parameter is specified when compiling PHP. Use thread safety.
PHP implementation
The thread safety implemented by PHP mainly uses the TSRM mechanism to protect global variables and static The variables are isolated, and global variables and static variables are copied to each thread. Each thread uses a backup of the main thread, thus avoiding variable conflicts and thread safety issues. (Recommended study: PHP video tutorial)
PHP’s encapsulation of multi-threads ensures thread safety. Programmers do not need to consider adding various locks to global variables to avoid read and write conflicts. At the same time, It also reduces the chance of errors, and the code written is safer.
But the result is that once the sub-thread starts running, the main thread can no longer adjust the running details of the sub-thread, and the thread loses the ability to transmit messages between threads through global variables to a certain extent. .
At the same time, after PHP turns on the thread safety option, there will be additional losses when using the TSRM mechanism to allocate and use variables. Therefore, in a PHP environment that does not require multi-threading, use the ZTS (non-thread safety) version of PHP. Just fine.
Example code
The following is a thread class used to request a certain interface. Next, write two multi-threaded application examples based on it:
class Request extends Thread { public $url; public $response; public function __construct($url) { $this->url = $url; } public function run() { $this->response = file_get_contents($this->url); } }
Asynchronous request
Split the synchronous request into multiple threads and asynchronous calls to improve the program operating efficiency.
$chG = new Request("www.google.com"); $chB = new Request("www.baidu.com"); $chG ->start(); $chB ->start(); $chG->join(); $chB->join(); $gl = $chG->response; $bd = $chB->response;
The above is the detailed content of How to implement multi-threading in php. For more information, please follow other related articles on the PHP Chinese website!