PHP 多进程实践(3)
Release: 2016-06-13 12:56:26
Original
1077 people have browsed it
PHP 多进程实践(三)
5. windows多线程
windows系统不支持pcntl函数,幸好有curl_multi_exec()这个工具,利用内部的多线程,访问多个链接,每个链接可以作为一个任务。
编写脚本 test1.php
<?php date_default_timezone_set( 'Asia/Chongqing');
$tasks = array(
'http://localhost/feedbowl/t2.php?job=task1',
'http://localhost/feedbowl/t2.php?job=task2',
'http://localhost/feedbowl/t2.php?job=task3'
);
$mh = curl_multi_init();
foreach ($tasks as $i => $task){
$ch[$i] = curl_init();
curl_setopt($ch[$i], CURLOPT_URL, $task);
curl_setopt($ch[$i], CURLOPT_RETURNTRANSFER, 1);
curl_multi_add_handle($mh, $ch[$i]);
}
do {$mrc = curl_multi_exec($mh,$active); } while ($mrc == CURLM_CALL_MULTI_PERFORM);
while ($active && $mrc == CURLM_OK) {
if (curl_multi_select($mh) != -1) {
do {$mrc = curl_multi_exec($mh, $active); } while ($mrc == CURLM_CALL_MULTI_PERFORM);
}
}
// completed, checkout result
foreach ($tasks as $j => $task){
if (curl_error($ch[$j])){
echo "task ${j} [$task ] error " , curl_error($ch[$j]), "\r\n" ;
} else {
echo "task ${j} [$task ] get: \r\n" , curl_multi_getcontent($ch[$j]), "\r\n" ;
}
}
?>
Copy after login
编写脚本 test2.php
<?php date_default_timezone_set( 'Asia/Chongqing');
echo "child start, pid ", getmypid(), "\r\n" ;
for ($i=0; $i<5; ++$i){
beep();
}
exit (0);
// ***
function beep(){
echo getmypid(), "\t" , date('Y-m-d H:i:s' , time()), "\r\n";
sleep(1);
}
?>
Copy after login
用命令行运行
#php -f test1.php &
输出结果
task 0 [http://localhost/feedbowl/t2.php?job=task1] get:
child start, pid 5804
5804 2013-01-15 20:22:35
5804 2013-01-15 20:22:36
5804 2013-01-15 20:22:37
5804 2013-01-15 20:22:38
5804 2013-01-15 20:22:39
task 1 [http://localhost/feedbowl/t2.php?job=task2] get:
child start, pid 5804
5804 2013-01-15 20:22:35
5804 2013-01-15 20:22:36
5804 2013-01-15 20:22:37
5804 2013-01-15 20:22:38
5804 2013-01-15 20:22:39
task 2 [http://localhost/feedbowl/t2.php?job=task3] get:
child start, pid 5804
5804 2013-01-15 20:22:35
5804 2013-01-15 20:22:36
5804 2013-01-15 20:22:37
5804 2013-01-15 20:22:38
5804 2013-01-15 20:22:39
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
Latest Articles by Author
-
2024-10-22 09:46:29
-
2024-10-13 13:53:41
-
2024-10-12 12:15:51
-
2024-10-11 22:47:31
-
2024-10-11 19:36:51
-
2024-10-11 15:50:41
-
2024-10-11 15:07:41
-
2024-10-11 14:21:21
-
2024-10-11 12:59:11
-
2024-10-11 12:17:31