Home  >  Article  >  Backend Development  >  How to implement multi-threading in PHP

How to implement multi-threading in PHP

墨辰丷
墨辰丷Original
2018-06-09 11:25:093800browse

This article mainly introduces the method of implementing multi-threading in PHP. Interested friends can refer to it. I hope it will be helpful to everyone.

The example in this article describes how to implement multi-threading in PHP shell, 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! First look at the code of test.php:

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

Notice that the php code is requested Is there an & symbol in the line? This is the key. If it is not added, 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 is processed at the same time, thus achieving multi-threading. Run the shell below to see the effect. Here you will see 10 test.php processes running again, and then use the Linux timer to request this shell regularly. , very useful when processing some tasks that require multi-threading, such as batch downloading!

Summary: The above is the entire content of this article, I hope it will be helpful to everyone's study.

Related recommendations:

php techniques for caching through file storage

Detailed explanation of php's function for uploading image files

php uses regular expressions to extract links in the content

php recursive traversal to achieve infinite classification

php process control and mathematical operations

The above is the detailed content of How to implement multi-threading in PHP. For more information, please follow other related articles on the PHP Chinese website!

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