The example in this article describes the implementation method of multi-thread concurrency in PHP. Share it with everyone for your reference, the details are as follows:
Multi-threading in Java is a new thread thing. PHP relies on Apache and there is a multi-threading method at the bottom of Linux.
Here is how to simulate PHP concurrency if you cannot control the Apache server
<?php if(function_exists('date_default_timezone_set')) { date_default_timezone_set('PRC'); } function a() { $time = time(); sleep(3); $fp = fopen('result_a'.$time.'.log', 'w'); fputs($fp, 'Set in ' . Date('h:i:s', time()) . (double)microtime() . "rn"); fclose($fp); } function b() { $time = time(); sleep(3); $fp = fopen('result_b'.$time.'.log', 'w'); fputs($fp, 'Set in ' . Date('h:i:s', time()) . (double)microtime() . "rn"); fclose($fp); } if(!isset($_GET['act'])) $_GET['act'] = 'a'; if($_GET['act'] == 'a') { a(); } else if($_GET['act'] == 'b') b(); ?>
The above code writes a file locally.
If you visit localhost/a.php and open two browser tabs at the same time as quickly as possible, you will find that the difference in creation time of the two files is 3 seconds
But if you visit localhost/a.php?act=b another one Visit /a.php?act=a and you will find that the two files were created at almost the same time.
For apache, the same URL means a thread (or process), but different URLs mean concurrency.
If there is a download action inside php
function runThread() { down("http://localhost/test/a.php?act=a"); } if($_GET['act'] == 'run') { echo 'start:'; runThread(); echo ' End'; }
http://localhost/test/a.php?act=run
http://localhost/test/a.php?act=run&s=2
As long as the host If the accessed URLs are different, they are considered to be different processes, which means concurrency. The file creation time is not 3 seconds
Friends who have a local Linux server can also use Linux to simulate concurrency
<?php for ($i=0;$i<10;$i++) { echo $i; sleep(5); } ?>
Save the above as test.php, and then write a SHELL code
#!/bin/bash for i in 1 2 3 4 5 6 7 8 9 10 do php -q test.php & done
More PHP will convert the entire website For a summary of methods for generating pure static HTML web pages, please pay attention to the PHP Chinese website for related articles!