(Pseudo) Multithreading and Multiprocessing in PHP_PHP Tutorial
(pseudo) multi-threading: with the help of external force
Utilize the multi-threading of the WEB server itself for processing, and call the program we need to implement multi-threading multiple times from the WEB server.
QUOTE:
We know that PHP itself does not support multi-threading, but our WEB server does support multi-threading.
That is to say, multiple people can access it at the same time. This is also the basis for me 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 these 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, you can control which program a.php runs through parameters.
Look at an example below:
[php] view plaincopy- function runThread(){
- $fp = fsockopen('localhost', 80, $errno, $errmsg);
- fputs($fp, "GET /a.php?act=brnrn");//The second parameter here is the request header specified in the HTTP protocol. If you don’t understand, please see the definition in the 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 will be nothing like
The synchronize method in Java. So how should we do 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, so in multi-threaded PHP
Do not write data to the same file. If you must write, use other methods for synchronization. For example, call flock to lock the file, etc. or create a temporary file
And wait for the file to disappear in another thread while(file_exits('xxx')); This means that when this temporary file exists, it means that the thread is actually operating
If this file no longer exists, it means that other threads have released this.
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, like fgets
Such a function returns immediately. So there will be problems when reading and writing data. If blocking mode is used, the program is not multi-threaded. It has to wait for the above return before executing
The following program. So if you need to exchange data, you can finally use external files or data to complete it. If you really want it, use socket_set_nonblock($fp) to achieve it.
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 form, you can use multiple threads at the same time
Read different pages.
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
This technology. Because both programs have to continuously connect to their servers to read information and save it to the database. Utilizing this technique just eliminates the bottle while waiting for a response
Neck.
Multi-process: Use PHP’s Process Control Functions (PCNTL/thread control function)
Function reference can be found at: http://www.php.net/manual/zh/ref.pcntl.php
Can only be used on Unix Like OS, not available on Windows.
When compiling php, you need to add --enable-pcntl, and it is recommended to run it only in CLI mode, not in a WEB server environment.
The following is a short test code:
- declare(ticks=1);
- $bWaitFlag = FALSE; /// Whether to wait for the process to end
- $intNum = 10; $pids = array
- (); 🎜> echo ("Startn");
- for($i = 0; $i
- $intNum; $i++) { $pids[$i] = pcntl_fork(); /// Spawn child process , and start the trial run code from the current line, and do not inherit the data information of the parent process
- if(!$pids[ $i
- ]) { // Child process process code segment_Start $str
- ="";
- sleep(5+$i); for
- ($j=0; $j
- $i;$j++) {$str.="*";} echo "$i -> " . time() . " $str n "
- ; exit(); // Child process process code segment_End
- }
- } if
- ( $bWaitFlag
- )
- { for( $i
- = 0; $intNum
- ; $i++) { pcntl_waitpid($pids[$i], $status , WUNTRACED);
- echo "wait $i -> " . time() . "n" ;
- } } echo ( "Endn"
- );
- The running results are as follows:
CODE:[Copy toclipboard][qiao@oicq qiao]$ phptest.php
Start
End
[qiao@oicq qiao]$ ps -aux | grep "php"
qiao 32275 0.0 0.5 49668 6148pts/1 S 14:03 0:00/usr/local/php4/b
qiao 32276 0.0 0.5 49668 6152pts/1 S 14:03 0:00/usr/local/php4/b
qiao 32277 0.0 0.5 49668 6152pts/1 S 14:03 0:00/usr/local/php4/b
qiao 32278 0.0 0.5 49668 6152pts/1 S 14:03 0:00/usr/local/php4/b
qiao 32279 0.0 0.5 49668 6152pts/1 S 14:03 0:00/usr/local/php4/b
qiao 32280 0.0 0.5 49668 6152pts/1 S 14:03 0:00 /usr/local/php4/b
qiao 32281 0.0 0.5 49668 6152pts/1 S 14:03 0:00/usr/local/php4/b
qiao 32282 0.0 0.5 49668 6152pts/1 S 14:03 0:00/usr/local/php4/b
qiao 32283 0.0 0.5 49668 6152pts/1 S 14:03 0:00/usr/local/php4/b
qiao 32284 0.0 0.5 49668 6152pts/1 S 14:03 0:00/usr/local/php4/b
qiao 32286 0.0 0.0 1620 600pts/1 S 14:03 0:00 grep php
[qiao@oicq qiao]$ 0 -> 1133503401
1 -> 1133503402 *
2 -> 1133503403 **
3 -> 1133503404 ***
4 -> 1133503405 ****
5 -> 1133503406 *****
6 -> 1133503407 ******
7 -> 1133503408 *******
8 -> 1133503409 ********
9 -> 1133503410 *********[qiao@oicq qiao]$
如果$bWaitFlag=TURE,则结果如下:CODE:[Copy toclipboard][qiao@oicq qiao]$ phptest.php
Start
0 -> 1133503602
wait 0 -> 1133503602
1 -> 1133503603 *
wait 1 -> 1133503603
2 -> 1133503604 **
wait 2 -> 1133503604
3 -> 1133503605 ***
wait 3 -> 1133503605
4 -> 1133503606 ****
wait 4 -> 1133503606
5 -> 1133503607 *****
wait 5 -> 1133503607
6 -> 1133503608 ******
wait 6 -> 1133503608
7 -> 1133503609 *******
wait 7 -> 1133503609
8 -> 1133503610 ********
wait 8 -> 1133503610
9 -> 1133503611 *********
wait 9 -> 1133503611
End
[qiao@oicq qiao]$
从 多进程的例子可以看出,使用pcntl_fork()之后,将生成一个子进程,而且子进程运行的代码,从pcntl_fork()之后的代码开始,而子进 程不继承父进程的数据信息(实际上是把父进程的数据做了一个全新的拷贝),因而使用if(!$pids[$i]) 来控制子进程实际运行的代码段。更详细的研究出于时间关系,暂时没有进行,你可以参考我给出的手册的链接。
[文章二] 尝试php命令行脚本多进程并发执行作者:dulao5
来源:http://dulao5.blog.hexun.com/3726837_d.html除了fork, cli下的并发方式还有一种,看我的例子:
php不支持多线程,但是我们可以把问题转换成“多进程”来解决。由于php中的pcntl_fork只有unix平台才可以使用,所以本文尝试使用popen来替代。
下面是一个例子:被并行调用的子程序代码:
[php] view plaincopy- if($argc==1){
- echo("argvn");
- }
- $arg = $argv[1];
- for($i=0; $i$i++)
- {
- echo($i.".1.".time()." exec $arg n");
- if($arg=='php2'){
- sleep(1);
- echo($i.".2.".time()." exec $arg n");
- sleep(1);
- }else{
- sleep(1);
- }
- }
- ?>
主调用者程序,由他调用子进程,同时并发的收集子程序的输出
[php] view plaincopy- error_reporting(E_ALL);
- $handle1 = popen('php sub.php php1', 'r');
- $handle2 = popen('php sub.php php2', 'r');
- $handle3 = popen('php sub.php php3', 'r');
- echo "'$handle1'; " . gettype($handle1) . "n";
- echo "'$handle2'; " . gettype($handle2) . "n";
- echo "'$handle3'; " . gettype($handle3) . "n";
- //sleep(20);
- while(!feof($handle1) || !feof($handle2) || !feof($handle3) )
- {
- $read = fgets($handle1);
- echo $read;
- $read = fgets($handle2);
- echo $read;
- $read = fgets($handle3);
- echo $read;
- }
- pclose($handle1);
- pclose($handle2);
- pclose($handle3);
下面是我机器上的输出:
C:my_hunter>php exec.php
'Resource id #4'; resource
'Resource id #5'; resource
'Resource id #6'; resource
0.1.1147935331 exec php1
0.1.1147935331 exec php2
0.1.1147935331 exec php3
1.1.1147935332 exec php1
0.2.1147935332 exec php2
1.1.1147935332 exec php3
2.1.1147935333 exec php1
1.1.1147935333 exec php2
2.1.1147935333 exec php3
3.1.1147935334 exec php1
1.2.1147935334 exec php2
3.1.1147935334 exec php3
4.1.1147935335 exec php1
2.1.1147935335 exec php2
4.1.1147935335 exec php3
5.1.1147935336 exec php1
2.2.1147935336 exec php2
5.1.1147935336 exec php3
6.1.1147935337 exec php1
3.1.1147935337 exec php2
6.1.1147935337 exec php3
7.1.1147935338 exec php1
3.2.1147935338 exec php2
7.1.1147935338 exec php3
8.1.1147935339 exec php1
4.1.1147935339 exec php2
8.1.1147935339 exec php3
9.1.1147935340 exec php1
4.2.1147935340 exec php2
9.1.1147935340 exec php3
5.1.1147935341 exec php2
5.2.1147935342 exec php2
6.1.1147935343 exec php2
6.2.1147935344 exec php2
7.1.1147935345 exec php2
7.2.1147935346 exec php2
8.1.1147935347 exec php2
8.2.1147935348 exec php2
9.1.1147935349 exec php2
9.2.1147935350 exec php2**总结:**
**主程序循环等待子进程, 通过fgets或fread 把子进程的输出获取出来 , 从时间戳上看,的确实现了并发执行。**
-----------------------------------------------
以后的改进:* popen打开的句柄是单向的,如果需要向子进程交互,可以使用proc_open
* 使用数组和子函数代替while(!feof($handle1)|| !feof($handle2) || !feof($handle3) )这种龌龊的写法
* 用fread一次把子进程已经产生的输出取完,而不是每次一行。一个并发执行shell任务的调度者,本程序读取一个任务文件,把里面的每行命令并发执行, 可以设置同时存在的子进程数目:
[php] view plaincopy- /*
- Main Task Manager
- Concurrent execution sub-task list
- */
- include("../common/conf.php");
- include("../common/function.php");
- //Number of opened processes
- $exec_number = 40 ;
- /***** main ********/
- if($argc==1){
- echo("argvn");
- }
- $taskfile = $argv[1];
- //tasklist
- $tasklist = file($taskfile);
- $tasklist_len = count($tasklist);
- $tasklist_pos = 0;
- $handle_list = array();
- while(1)
- {
- //If the child process list is free, fill in the child process list
- if($exec_number > count( $handle_list) &&
- $tasklist_pos $tasklist_len)
- {
- for($i=$tasklist_pos; $i$tasklist_len; )
- $command = $tasklist[$i]; 🎜> $handle_list
- [] = popen($command , "r" ); tolog( "begin task t "
- .$tasklist[$i]); $i
- ++; if
- ($exec_number == count( $handle_list)) break;
- $tasklist_pos =
- $i; }
- //If the child process list is empty, exit
- if (0 ==
- count($handle_list)) {
- break ;
- }
- //Check the output of the child process list, close the stopped child process and record it
- $end_handle_keys = array();
- foreach($handle_list as $key => $handle)
- {
- //$str = fgets($handle, 65536);
- $str = fread($handle, 65536);
- echo($str);
- if(feof($handle))
- $end_handle_keys[] = $key; pclose(
- $handle);
- }
- //Kick out the stopped child process
- foreach
- ($end_handle_keys as $key) {
- unset($handle_list
- [$key]); //var_dump($handle_list);
- //exit;
- }
- }
- tolog("nn************************end********************** *****nn"
- , "" , true); Attach a piece of code for Socket multi-process reception:
- do {
- if (($msgsock = socket_accept($sock))
- echo "socket_accept() failed: reason: " . socket_strerror($msgsock) . "n";
- break;
- }
- $pid = pcntl_fork();
- if ($pid == -1) {
- die('could not fork');
- } else if (!$pid) {
- .....
- socket_write($msgsock, $msg, strlen($msg));
- do {
- ......
- } while (true);
- socket_close($msgsock);
- }
- } while (true);
原文地址:http://www.alixixi.com/program/a/2008050731686.shtml

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python are both high-level programming languages that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values and handle functions that may return null values.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Dreamweaver Mac version
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

WebStorm Mac version
Useful JavaScript development tools