首页 > 系统服务 > 详细

多进程,进程池。

时间:2016-10-18 15:55:26      阅读:229      评论:0      收藏:0      [点我收藏+]

1.多进程的调用

1.1 multiprocessing调用

 1 from multiprocessing import Process
 2 import time
 3 def f(name):
 4     time.sleep(1)
 5     print(‘hello‘, name,time.ctime())
 6 
 7 if __name__ == ‘__main__‘:
 8     p_list=[]
 9     for i in range(3):
10         p = Process(target=f, args=(‘alvin‘,))
11         p_list.append(p)
12         p.start()
13     for i in p_list:
14         i.join()
15     print(‘end‘)

运用for循环开启了3个子进程,全都join在主进程中。运行结果:

1 hello alvin Tue Oct 18 15:10:28 2016
2 hello alvin Tue Oct 18 15:10:28 2016
3 hello alvin Tue Oct 18 15:10:28 2016
4 end

结果显示:三个字符串同时打印出来。达到了多进程的目的。

1.2类来调用

 1 from multiprocessing import Process
 2 import time
 3 
 4 class MyProcess(Process):
 5     def __init__(self):
 6         super(MyProcess, self).__init__()
 7         # self.name = name
 8 
 9     def run(self):
10         time.sleep(1)
11         print (‘hello‘, self.name,time.ctime())
12 
13 
14 if __name__ == ‘__main__‘:
15     p_list=[]
16     for i in range(3):
17         p = MyProcess()
18         p.start()
19         p_list.append(p)
20 
21     for p in p_list:
22         p.join()
23 
24     print(‘end‘)

同时开启了4个进程,但是并没有直接p.run()指令,但是结果显示:

1 hello MyProcess-1 Tue Oct 18 15:13:46 2016
2 hello MyProcess-2 Tue Oct 18 15:13:46 2016
3 hello MyProcess-3 Tue Oct 18 15:13:46 2016
4 end

可以看出:run函数是被自动执行的。self.name因为是被默认为进程的名称。

小总结:1.上述的四个进程在执行的过程中实现了真正的并发。但是在多过CPU个数的时候。。。

    2.子进程的创建时将主进程完全copy一遍,很占资源的一种形式。

小细节:win系统中,创建子进程必须加main来标识主,子进程的不同。上述的例子中print(end)若是不在main中会产生影响。

2.进程之间的关系

 1 from multiprocessing import Process
 2 import os
 3 import time
 4 def info(title):
 5     print(title)
 6     print(‘module name:‘, __name__)
 7     print(‘parent process:‘, os.getppid())
 8     print(‘process id:‘, os.getpid())
 9 
10 
11 def f(name):
12     info(‘\033[31;1mfunction f\033[0m‘)
13     print(‘hello‘, name)
14 
15 if __name__ == ‘__main__‘:
16     info(‘\033[32;1mmain process line\033[0m‘)
17     time.sleep(5)
18     p = Process(target=info, args=(‘bob‘,))
19     p.start()
20     p.join()

上述的代码中展示了进程的father进程的ID和自身的ID (通过os模块的getppid和getppid)

1 main process line
2 module name: __main__
3 parent process: 11156
4 process id: 4592
5 bob
6 module name: __mp_main__
7 parent process: 4592
8 process id: 7280

结果表明:主进程的名字为main,并且父进程为pycharm的pid。子进程的name不为main所以不会执行main中内容。

多进程,进程池。

原文:http://www.cnblogs.com/khal-Cgg/p/5973536.html

踩
(0)
赞
(0)
   
举报
评论 一句话评论(0)
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!