Original: https://www.w3cschool.cn/php/php-thread.html
------------------------------------------------------------------easy-to-understand PHP multithreading solution created by Youj, Carrie last modified 2016-12-01
When we do the project, some needs, especially the data response processing takes a lot of time, because PHP is a short life cycle of the scripting language, to the default of 30 seconds, PHP data processing is not completed, PHP life cycle is over. At this point, you need to use asynchronous concurrency processing policy, that is, a PHP call can make multiple requests, these requests are not executed sequentially, but can be executed asynchronously, some requests for processing data in the background, some requests to accept the background response State, based on the state, to do some simple interaction with the user. But the problem comes, we all know that PHP itself is not support multi-threaded, then how to implement the multi-threaded PHP?
One, PHP simulation implementation of three ways of multithreading
1. PHP Multithreading under Linux
The following is the Pcntl_fork function that originates from PHP. Because this function relies on the implementation of the operating system fork, the things in this article only apply to Linux/unix. So let's take a look at the use of this function. This is what the PHP manual says:
<?php$pid = pcntl_fork();if ($pid == -1) { die(‘could not fork‘);} else if ($pid) { // we are the parent pcntl_wait($status); //Protect against Zombie children} else { // we are the child}?>
Creating a subprocess through Pcntl_fork, if the return value is-1, indicates that the child process creation failed. The process ID that was created is returned to the parent process, and 0 is returned to the child process. It's hard to understand, so it should be written like this:
<?php$pid = pcntl_fork();if($pid == -1){ //创建失败咱就退出呗,没啥好说的 die(‘could not fork‘);}else{ if($pid){ //从这里开始写的代码是父进程的,因为写的是系统程序,记得退出的时候给个返回值 exit(0); } else{ //从这里开始写的代码都是在新的进程里执行的,同样正常退出的话,最好也给一个返回值 exit(0); }}?>
Such a change to understand more, if your parent process want to know that the child process gracefully exit, you can add the previous pcntl_wait.
2. by Stream_socket_client Way
function Sendstream(){$english _format_number = Number_format ($number,4,‘.‘,‘‘);echo $english _format_number;Exit (); $timeout =10; $result =Array (); $sockets =Array (); $convenient _read_block =8192; $host ="Test.local.com"; $sql ="Select waybill_id,order_id from Xm_waybill where status>40 order by update_time desc LIMIT 1"; $data = Yii::app ()->db->createcommand ($sql)->queryall (); $id =0;foreach ($dataas $k = = $v) {if ($k%2 = =0) {$send _data[$k] [' body '] = Noticeorder::getsenddata ($v [' waybill_id ']); }else {$send _data[$k] [' Body '] =Array ($v [' order_id '] =Array' Extra ' =16)); } $data = Json_encode ($send _data[$k] [' Body ']); $s = stream_socket_client ($host.":", $errno, $errstr, $timeout, Stream_client_async_connect | Stream_client_connect);if ($s) {$sockets [$id + +] = $s; $http _message ="Get/php/test.php?data=". $data."Http/1.0\r\nhost:". $host."\r\n\r\n"; Fwrite ($s, $http _message); }else {Echo"Stream". $id."Failed to open correctly."; } }while (count ($sockets)) {$read = $sockets; Stream_select ($read, $w =NULL, $e =NULL, $timeout);if (count ($read)) {/* Stream_select generally shuffles $read, so we need to compute from which socket (s) we ' re reading. */foreach ($read as $r) {$id = Array_search ($r, $sockets); $data = Fread ($r, $convenient _read_block); if (strlen ($data) = = 0) { echo "Stream". $id. "closes at". Date (' h:i:s '). ".<br>"; Fclose ($R); unset ($sockets [$id]);} else {$result [$id] = $data;}} } Else {/ * A time-out means that *all* streams has failed to receive A response. */ echo "time-out!\ n "; Break ;} } print_r ($result); }
3, through multi-process instead of multithreading
function Daemon($func _name, $args, $number) {Whiletrue) {$pid =pcntl_fork ();if ($pid = =-1) {Echo"Fork process fail";Exit (); }ElseIf ($pid) {The child process that was createdstatic $num =0; $num + +;if ($num >= $number) {When the number of processes reaches a certain number, the child process is recycled. Pcntl_wait ($status); $num--; } }else{0 is created by a child process, then goes directly to the working stateif (function_exists ($func _name)) {while (true) {$ppid =posix_getpid (); Var_dump ($ppid); Call_user_func_array ($func _name, $args); Sleep (2);}} else{ echo "function is not exists";} exit ();} }} function worker($args) { //do something} daemon (' worker ',Array (1),2);
Second, the real implementation of PHP Multi-threading Method PHP Real multi-threaded implementation, through the installation of PHP extension pthread can do.
Click here to download but this download is version 3 is PHP 7 to use, we need to make version 2
Then refresh the page as follows and drag to the bottom:
Next page found for version 2
Download down, this v2 is php5 can use
Download down, install:
Or, you download it directly:
cd /tools wget https://github.com/krakjoe/pthreads/archive/v2.0.10.zip unzip v2.0.10.zip cd pthreads-2.0.10 /usr/local/php/bin/phpize ./configure --with-php-config=/usr/local/php/bin/php-config make make install
Note: Your PHP needs to be turned on when compiling –enable-maintainer-zts
./configure --prefix=/usr/local/php --disable-fileinfo --enable-fpm --with-config-file-path=/etc --with-config-file-scan-dir=/etc/php.d --with-openssl --with-zlib --with-curl --enable-ftp --with-gd --with-xmlrpc
vim /etc/php.ini 添加extension=pthreads.so
重启php /etc/init.d/php-fpm restart
[Go] Easy-to-understand PHP multithreading solution