Table of Contents
Two methods to implement multi-threading in PHP
Home Backend Development PHP Tutorial Two methods to implement multi-threading in PHP_PHP tutorial

Two methods to implement multi-threading in PHP_PHP tutorial

Jul 13, 2016 am 09:44 AM
php indivual accomplish method of Simple thread

Two methods to implement multi-threading in PHP

Methods to implement multi-threading in PHP shell

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: ls

PHP code:

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!

Using WEB server to implement multi-threading in php

Suppose we are running the file a.php now. But I request the WEB server to run another b.php in the program, then the two files will be executed at the same time. (PS: After a link request is sent , the WEB server will execute it, regardless of whether the client has exited)

Sometimes, what we want to run is not another file, but a part of the code in this file. What should we do?
In fact, parameters are used to control which program a.php runs.

Look at an example below:

//a.php,b.php

PHP code:-------------------------------------------------- ----------------------------------

Function runThread()
{
$fp = fsockopen('localhost', 80, $errno, $errmsg);
                                                                                                                                                                                                                                                                                                     //If you don’t understand, please see the definition in RFC
                                                            fclose($fp);
}

Function a()
{
          $fp = fopen('result_a.log', 'w');
              fputs($fp, 'Set in ' . Date('h:i:s', time()) . (double)microtime() . "rn");
                                                           fclose($fp);                                                              }

Function b()
{
          $fp = fopen('result_b.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')
{
        runThread();
a();
}
​ else if($_GET['act'] == 'b') b();
?>
-------------------------------------------------- ----------------------------------


Open result_a.log and result_b.log and compare the access times of the two files. You will find that these two are indeed running in different threads. Some times are exactly the same.

The above is just a simple example, you can improve it into other forms.

Now that multi-threading is available in PHP, a problem arises, which is synchronization. We know that PHP itself does not support multi-threading. So there is no method like synchronize in Java. So what should we do? Doing it.

1. Try not to access the same resource to avoid conflicts. But you can operate the database at the same time. Because the database supports concurrent operations, do not write data to the same file in multi-threaded PHP. If necessary If you want to write, use other methods for synchronization. For example, call flock to lock the file, etc. Or create a temporary file and wait for the disappearance of the file in another thread while(file_exits('xxx')); This is equivalent to When this temporary file exists, it means that the thread is actually operating

If there is no such file, it means that other threads have released it.

2. Try not to read data from the socket that runThread takes after executing fputs. Because to achieve multi-threading, it is necessary to use non-blocking mode. That is, return immediately when functions like fgets are used. So read and write data Problems will arise. If blocking mode is used, the program is not multi-threaded. It has to wait for the return of the above before executing the following program. So if data needs to be exchanged, it can be completed using external files or data. If you really want it, just Use socket_set_nonblock($fp) to implement.


Having said so much, does this have any practical significance? When is it necessary to use this method?
The answer is yes. As we all know, in an application that constantly reads network resources, the speed of the network is the bottleneck. If you adopt this method, you can read different pages with multiple threads at the same time.

I made a program that can search for information from shopping mall websites such as 8848 and soaso. There is also a program that reads business information and company directories from the Alibaba website and also uses this technology. Because both programs have to continuously connect to their servers to read information and save it to the database. Utilizing this technology eliminates the bottleneck of waiting for a response.


Three ways to simulate multi-threading in PHP

The PHP language itself does not support multi-threading. I summarized the methods on the Internet for simulating multi-threading in PHP. Generally speaking, they all make use of the multi-threading capabilities of PHP’s good partners. PHP is good Partners refer to LINUX and APACHE, LAMP.

In addition, since it is simulated, it is not true multi-threading. In fact, it is just multi-process. Process and thread are two different concepts. Well, the following methods are all found from the Internet.

1. Using LINUX operating system

for ($i=0;$i<10;$i ) {
echo $i;
sleep(5);
}
?>

Save the above into 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

2. Use fork child process (in fact, it also uses the LINUX operating system)

declare(ticks=1);
$bWaitFlag = FALSE; /// Whether to wait for the process to end
$intNum = 10; /// Total number of processes
$pids = array(); /// Process PID array
echo ("Startn");
for($i = 0; $i < $intNum; $i ) {
$pids[$i] = pcntl_fork();/// Generate a child process, and start the test run code from the current line, and do not inherit the data information of the parent process
if(!$pids[$i]) {
// Subprocess process code segment_Start
$str="";
sleep(5 $i);
for ($j=0;$j<$i;$j ) {$str.="*";}
echo "$i -> " . time() . " $str n";
exit();
// Subprocess process code segment_End
}
}
if ($bWaitFlag)
{
for($i = 0; $i < $intNum; $i ) {
pcntl_waitpid($pids[$i], $status, WUNTRACED);
echo "wait $i -> " . time() . "n";
}
}
echo ("Endn");
?>

3. Using WEB SERVER, PHP does not support multi-threading, but APACHE does, haha.

Suppose we are running the document a.php. But I also request the WEB server to run another b.php in the program

Then the two documents will be executed at the same time. (The code is the same as above)

Of course, you can also leave the parts that require multi-threading to JAVA and then call them in PHP, haha.

system('java multiThread.java');
?>

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/1049987.htmlTechArticleTwo methods to implement multi-threading in PHP Methods to implement multi-threading in PHP shell First write a simple php code, here In order to make the script execution time longer and see the effect more easily, sleep for a while, haha! First...
Statement of this Website
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

CakePHP Project Configuration CakePHP Project Configuration Sep 10, 2024 pm 05:25 PM

In this chapter, we will understand the Environment Variables, General Configuration, Database Configuration and Email Configuration in CakePHP.

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

CakePHP Date and Time CakePHP Date and Time Sep 10, 2024 pm 05:27 PM

To work with date and time in cakephp4, we are going to make use of the available FrozenTime class.

CakePHP File upload CakePHP File upload Sep 10, 2024 pm 05:27 PM

To work on file upload we are going to use the form helper. Here, is an example for file upload.

CakePHP Routing CakePHP Routing Sep 10, 2024 pm 05:25 PM

In this chapter, we are going to learn the following topics related to routing ?

Discuss CakePHP Discuss CakePHP Sep 10, 2024 pm 05:28 PM

CakePHP is an open-source framework for PHP. It is intended to make developing, deploying and maintaining applications much easier. CakePHP is based on a MVC-like architecture that is both powerful and easy to grasp. Models, Views, and Controllers gu

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

CakePHP Creating Validators CakePHP Creating Validators Sep 10, 2024 pm 05:26 PM

Validator can be created by adding the following two lines in the controller.

See all articles