Python并发编程-多进程

                       作者:尹正杰

版权声明:原创作品,谢绝转载!否则将追究法律责任。

 

 

一.多进程相关概念

  由于Python的GIL全局解释器锁存在,多线程未必是CPU密集型程序的好的选择。

  多进程可以完全独立的进程环境中运行程序,可以较充分地利用多处理器。
  但是进程本身的隔离带来的数据不共享也是一个问题。而且线程比进程轻量级。

 

二.multiprocessing

 1 #!/usr/bin/env python
 2 #_*_conding:utf-8_*_
 3 #@author :yinzhengjie
 4 #blog:http://www.cnblogs.com/yinzhengjie
 5 
 6 import multiprocessing
 7 import datetime
 8 
 9 """
10   Process类遵循了Thread类的API,减少了学习难度。
11 
12   相比线程的方法,进程多出来几个方法需要注意下:
13     pid:
14       进程id
15     exitcode:
16       进程的退出状态码
17     terminate():
18       终止指定的进程
19 
20     先看一个例子,前面介绍的单线程、多线程比较的例子的多进程版本,具体代码如下所示。
21 """
22 
23 def calc(i):
24     sum = 0
25     for _ in range(1000000000):
26         sum += 1
27     return i,sum
28 
29 if __name__ == '__main__':
30     start = datetime.datetime.now()
31 
32     ps = []
33 
34     for i in range(4):
35         p = multiprocessing.Process(target=calc,args=(i,),name="calc-{}".format(i))
36         ps.append(p)
37         p.start()
38 
39     for p in ps:
40         p.join()
41         print(p.name,p.exitcode)
42 
43     delta = (datetime.datetime.now() - start).total_seconds()
44     print(delta)
45 
46     for p in ps:
47         print(p.name,p.exitcode)
48 
49     print("=== end ===")
calc-0 0
calc-1 0
calc-2 0
calc-3 0
47.011848
calc-0 0
calc-1 0
calc-2 0
calc-3 0
=== end ===
以上代码执行结果戳这里

相关文章:

  • 2021-12-04
  • 2021-12-04
  • 2021-08-19
  • 2022-01-15
猜你喜欢
  • 2022-12-23
  • 2021-09-19
  • 2021-07-28
  • 2022-12-23
  • 2021-06-09
  • 2021-12-04
  • 2021-12-04
相关资源
相似解决方案