File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change @@ -62,7 +62,7 @@ I am child process (86646) and my parent is (86645).
6262
6363# 多进程
6464
65- Python 提供了一个 [ multiprocessing] [ mp ] 模块,利用它,我们可以来编写跨平台的多进程程序。
65+ Python 提供了一个 [ multiprocessing] [ mp ] 模块,利用它,我们可以来编写跨平台的多进程程序,但是这里有一个坑,一样的代码在Windows和Linux下运行的结果可能不同 。
6666
6767我们先来看一个简单的例子,该例子演示了在主进程中启动一个子进程,并等待其结束,代码如下:
6868
@@ -94,6 +94,32 @@ Run child process test (10075)...
9494Process end.
9595```
9696
97+ ## multiprocessing与平台有关
98+
99+ ``` python
100+ import random
101+ import os
102+ from multiprocessing import Process
103+
104+ num = random.randint(0 , 100 )
105+
106+ def show_num ():
107+ print (" pid:{} , num is {} " .format(os.getpid(), num))
108+
109+ if __name__ == " __main__" :
110+ print (" pid:{} , num is {} " .format(os.getpid(), num))
111+ p = Process(target = show_num)
112+ p.start()
113+ p.join()
114+
115+ ```
116+ 在Windows下运行以上代码,输出的结果如下(你得到不一样的结果也是对的):
117+ ```
118+ pid:6504, num is 25
119+ pid:6880, num is 6
120+ ```
121+ 在Linux下运行以上代码,可以尝试一下,pid确实不同,但是得到的num一定相同。
122+
97123## 使用进程池创建多个进程
98124
99125在上面,我们只是创建了一个进程,如果要创建多个进程呢?Python 提供了** 进程池** 的方式,让我们批量创建子进程,让我们看一个简单的示例:
You can’t perform that action at this time.
0 commit comments