The so-called multithreading is multiple programs running concurrently, single-threaded: The execution of a logic, waiting to complete after the execution of another.
Multithreading: Several logic processing at the same time, do not need to wait for each other, improve the total execution time
Next, multithreading is implemented with curl
Implementing logic
1. fcsv.php is a CSV-generated file. Wait 10 seconds for the CSV file to be generated.
2. curl.php analog multi-threaded files. At the same time Curl requests fcsv.php.
If a single thread, the second CSV file needs to wait 10 seconds, the first CSV file ends before you start to do the action.
If multi-threading, it is also generating 5 CSV files at a time. Because it is parallel, the sum is 10 seconds.
Start on the code
fcsv.php
1<?PHP2 $p=isset($_post[' type ']) ?$_post[' type ']: 0;3 $fp=fopen("File/demo_csv".$p.". CSV "," a ");//Open the CSV file and create it if it does not exist4 $data _arr1=Array("10001", "10002", "10003", "10004", "10005");//first row of data5 $data _arr2=Array("20001", "20002", "20003", "20004", "20005");//second row of data6 $data _str1=implode(",",$data _arr1);//use ' split into string '7 $data _str2=implode(",",$data _arr2);//use ' split into string '8 $data _str=$data _str1." /n ".$data _str2." /n ";//Add line break9 fwrite($fp,$data _str);//Write DataTen fclose($fp);//Close file handle One Sleep(5); A return $p; -?>
curl.php
<?PHP$MH=curl_multi_init ();$conn= [];$res= [];$url= "localhost/fcsv.php"; for($i= 0;$i<=5;$i++) { $data=Array(' type ' = =$i); $conn[$i]=curl_init ($url); curl_setopt ($conn[$i],curlopt_returntransfer,1); curl_setopt ($conn[$i], Curlopt_postfields,$data); Curl_multi_add_handle ($MH,$conn[$i]);} Do{$n=curl_multi_exec ($MH,$active); } while($active); for($i= 0;$i<=5;$i++) { $res[$i]=curl_multi_getcontent ($conn[$i]); Curl_close ($conn[$i]);}Print_r($res);?>
Run the curl.php file
If a single thread, the second CSV file needs to wait 10 seconds, the first CSV file ends before you start to do the action.
If multi-threading, it is also generating 5 CSV files at a time. Because it is parallel, the sum is 10 seconds.
The file is generated at the same time, and after almost 10 seconds the browser returns a value to stop the request. Description of running multi-threaded
Simulate multithreading with curl