标签:
创建进程的类:Process([group [, target [, name [, args [, kwargs]]]]]),target表示调用对象,args表示调用对象的位置参数元组。kwargs表示调用对象的字典。name为别名。group实质上不使用。
import multiprocessing import time def worker(interval): n = 5 while n > 0: print("The time is {0}".format(time.ctime())) time.sleep(interval) n -= 1 if __name__ == "__main__": p = multiprocessing.Process(target = worker, args = (3,)) p.start() print "p.pid:", p.pid print "p.name:", p.name print "p.is_alive:", p.is_alive()
输出结果: p.pid: 8736 p.name: Process-1 p.is_alive: True The time is Tue Apr 21 20:55:12 2015 The time is Tue Apr 21 20:55:15 2015 The time is Tue Apr 21 20:55:18 2015 The time is Tue Apr 21 20:55:21 2015 The time is Tue Apr 21 20:55:24 2015
import multiprocessing import time class MyProcess(multiprocessing.Process): def __init__(self, interval): multiprocessing.Process.__init__(self) self.interval = interval def run(self): n = 5 while n > 0: print("the time is {0}".format(time.ctime())) time.sleep(self.interval) n -= 1 if __name__ == ‘__main__‘: p = MyProcess(3) p.start()
输出结果: the time is Wed Jul 20 22:44:16 2016 the time is Wed Jul 20 22:44:19 2016 the time is Wed Jul 20 22:44:22 2016 the time is Wed Jul 20 22:44:25 2016 the time is Wed Jul 20 22:44:28 2016
说明:自定义多线程类需要重写run方法,执行自定义类的实例时会自动调用run方法。
1)守护进程即守护主进程的进程,与主进程同生共死。
2)主进程退出时,守护进程也跟着退出。
3)默认情况下,创建的紫禁城程非守护进程,既主进程如果执行完毕的,而子进程没有执行完毕,主进程会等待子进程执行完毕后再退出。
4)设置守护进程的方法是 setDaemon = True。
def worker(interval): print("work start:{0}".format(time.ctime())); time.sleep(interval) print("work end:{0}".format(time.ctime())); if __name__ == "__main__": p = multiprocessing.Process(target = worker, args = (3,)) p.daemon = True p.start() print("end!")
输出结果: end!
输出结果只有一个end!,子进程随着主进程的消亡而消亡,因为设置了守护进程。
标签:
原文地址:http://www.cnblogs.com/9527chu/p/5690020.html