Home > php教程 > php手册 > body text

PHP的pcntl多进程用法实例

WBOY
Release: 2016-06-13 09:11:04
Original
964 people have browsed it

PHP的pcntl多进程用法实例

 这篇文章主要介绍了PHP的pcntl多进程用法,实例分析了pcntl操作多进程的使用技巧,非常具有实用价值,需要的朋友可以参考下

 

 

本文实例讲述了PHP的pcntl多进程用法。分享给大家供大家参考。具体分析如下:

PHP使用PCNTL系列的函数也能做到多进程处理一个事务。比如我需要从数据库中获取80w条的数据,再做一系列后续的处理,这个时候,用单进程?你可以等到明年今天了。所以应该使用pcntl函数了。

假设我想要启动20个进程,将1-80w的数据分成20份来做,主进程等待所有子进程都结束了才退出:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

$max = 800000;

$workers = 20;

$pids = array();

for($i = 0; $i

$pids[$i] = pcntl_fork();

switch ($pids[$i]) {

case -1:

echo "fork error : {$i} \r\n";

exit;

case 0:

$param = array(

'lastid' => $max / $workers * $i,

'maxid' => $max / $workers * ($i+1),

);

$this->executeWorker($input, $output, $param);

exit;

default:

break;

}

}

foreach ($pids as $i => $pid) {

if($pid) {

pcntl_waitpid($pid, $status);

}

}

这里当pcntl_fork出来以后,会返回一个pid值,这个pid在子进程中看是0,在父进程中看是子进程的pid(>0),如果pid为-1说明fork出错了。

使用一个$pids数组就可以让主进程等候所有进程完结之后再结束了

希望本文所述对大家的php程序设计有所帮助。

Related labels:
source:php.cn
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
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!