*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()之前设置。
创建函数并将其作为单个进程。
03 |
import multiprocessing |
08 |
print ( "The
time is {0}" . format (time.ctime())) |
11 |
if __name__ = = '__main__' : |
12 |
p = multiprocessing.Process(target = clock,
args = ( 15 ,)) |
将进程定义为类:
03 |
import multiprocessing |
06 |
class ClockProcess(multiprocessing.Process): |
07 |
def __init__( self ,interval): |
08 |
multiprocessing.Process.__init__( self ) |
09 |
self .interval = interval |
13 |
print ( "The
time is {0}" . format (time.ctime())) |
14 |
time.sleep( self .interval) |
16 |
if __name__ = = "__main__" : |
执行结果:
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 |
为了兼容windows而这样创建类,而且还要注意,在windows下,要在命令行才能执行,用IDE是不行的。
原文:http://www.erlangsir.com/2011/04/22/python-%E5%B9%B6%E5%8F%91-multiprocessing-process/