Home >Backend Development >PHP Tutorial >Simple example of multi-threading in php and shell

Simple example of multi-threading in php and shell

WBOY
WBOYOriginal
2016-07-25 08:57:10849browse
  1. //for loop
  2. for ($i = 0; $i < 10; $i++)
  3. {
  4. echo $i;
  5. sleep(5);
  6. }
Copy Code

Next, the shell comes into play, calling the php file: sleep.php, the code is as follows:

  1. #!/bin/bash
  2. #edit by bbs.it-home.org
  3. for i in 1 2 3 4 5
  4. do
  5. /usr/bin/php -r -q /data/website/ sleep.php &
  6. done
Copy code

Note: The key point of the above code is that you need to add an & symbol at the end of the line that requests the PHP code, otherwise multi-threading cannot be performed. & means that the service is pushed to the background for execution. Therefore, in each loop of the shell, you do not have to wait for all the PHP code to be executed before requesting the next file, but at the same time, that is, multi-threading is achieved. When you run the shell, you will see 10 test.php processes running. You can consider combining it with the Linux timer crontab to request the shell script regularly to handle some multi-threaded tasks, such as batch uploads or downloads.

Okay, that’s it for the example of combining php and shell to achieve multi-threading. I hope it will be helpful to everyone.



Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn