python mutiprocessing 入门示例,,multiprocess


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()之前设置。

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

#!/usr/bin/pythonimport multiprocessingimport timedef clock(interval):            while True:              print("The time is {0}".format(time.ctime()))              time.sleep(interval)if __name__ == '__main__':            p = multiprocessing.Process(target=clock, args=(15,))            p.start()

将进程定义为类:

#!/usr/bin/pythonimport multiprocessingimport timeclass ClockProcess(multiprocessing.Process):    def __init__(self,interval):            multiprocessing.Process.__init__(self)            self.interval = interval    def run(self):            while True:                print("The time is {0}".format(time.ctime()))                time.sleep(self.interval)if __name__ == "__main__":    p = ClockProcess(15)    p.start()

执行结果:

process startedThe time is Sun Dec 30 17:16:18 2012The time is Sun Dec 30 17:16:33 2012The time is Sun Dec 30 17:16:48 2012The time is Sun Dec 30 17:17:03 2012The time is Sun Dec 30 17:17:18 2012The time is Sun Dec 30 17:17:33 2012The time is Sun Dec 30 17:17:48 2012The time is Sun Dec 30 17:18:03 2012The time is Sun Dec 30 17:18:18 2012The time is Sun Dec 30 17:18:33 2012The time is Sun Dec 30 17:18:48 2012The time is Sun Dec 30 17:19:03 2012

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

评论关闭