现在的位置: 首页 > 综合 > 正文

Python 并发 multiprocessing-Process

2014年09月19日 ⁄ 综合 ⁄ 共 1666字 ⁄ 字号 评论关闭

*multiprocessing
支持子进程、通信和共享数据、执行不同形式的同步。
*Process
创建进程的类:Process([group [, target [, name [, args [, kwargs]]]]]),target表示调用对象,args表示调用对象的位置参数元组。kwargs表示调用对象的字典。Name为别名。Group实质上不使用。

方法有:is_alive()、.join([timeout])、run()、start()、terminate()。属性有:authkey、daemon(要通过start()设置)、exitcode(进程在运行时为None、如果为–N,表示被信号N结束)、name、pid。

Process类中,注意daemon是父进程终止后自动终止,且自己不能产生新进程,必须在start()之前设置。

创建函数并将其作为单个进程。

01 #!/usr/bin/python
02  
03 import multiprocessing
04 import time
05  
06 def clock(interval):
07             while True:
08               print("The
time is {0}"
.format(time.ctime()))
09               time.sleep(interval)
10  
11 if __name__ == '__main__':
12             = multiprocessing.Process(target=clock,
args
=(15,))
13             p.start()

将进程定义为类:

01 #!/usr/bin/python
02  
03 import multiprocessing
04 import time
05  
06 class ClockProcess(multiprocessing.Process):
07     def __init__(self,interval):
08             multiprocessing.Process.__init__(self)
09             self.interval = interval
10  
11     def run(self):
12             while True:
13                 print("The
time is {0}"
.format(time.ctime()))
14                 time.sleep(self.interval)
15  
16 if __name__ == "__main__":
17     = ClockProcess(15)
18     p.start()

执行结果:

01 jobin@jobin-desktop:~/work/python/fork$
python using_multiprocessing.py
02 The time is
Fri Apr 22 12:03:04 2011
03 The time is
Fri Apr 22 12:03:19 2011
04 The time is
Fri Apr 22 12:03:34 2011
05 The time is
Fri Apr 22 12:03:49 2011
06 The time is
Fri Apr 22 12:04:04 2011
07 The time is
Fri Apr 22 12:04:19 2011
08 The time is
Fri Apr 22 12:04:34 2011
09 The time is
Fri Apr 22 12:04:49 2011
10 .................

为了兼容windows而这样创建类,而且还要注意,在windows下,要在命令行才能执行,用IDE是不行的。

原文:http://www.erlangsir.com/2011/04/22/python-%E5%B9%B6%E5%8F%91-multiprocessing-process/

抱歉!评论已关闭.