Home > Article > Backend Development > How to implement multi-threading in PHP shell, how to implement multi-threading in phpshell_PHP tutorial
The example in this article describes how PHP shell implements multi-threading. Share it with everyone for your reference. The details are as follows:
Here is how to implement multi-threading with the help of shell scripts.
Write a simple php code first. In order to make the script execution time longer and see the effect more easily, sleep for a while, haha! Let’s take a look at the code of test.php first:
PHP code:
<?php for ($i=0;$i<10;$i++) { echo $i; sleep(10); } ?>
Look at the code of the shell script, it is very simple
#!/bin/bash for i in 1 2 3 4 5 6 7 8 9 10 do /usr/bin/php -q /var/www/html/test.php & done
Did you notice that there is an & symbol in the line that requests the PHP code? This is the key. Without it, multi-threading cannot be performed. & means that the service is pushed to the background for execution. Therefore, in each loop of the shell There is no need to wait for all the PHP code to be executed before requesting the next file. Instead, it is done at the same time, thus achieving multi-threading. Run the shell below to see the effect. Here you will see 10 test.php processes and then run. Then use the Linux timer to request this shell regularly, which is very useful when processing some tasks that require multi-threading, such as batch downloading!
I hope this article will be helpful to everyone’s PHP programming design.