Python之process(三)
1.Manager模块
#!/usr/bin/env python # -*- coding:utf8 -*- # @Time : 2017/12/12 14:48 # @Author : hantong # @File : process_4.py import multiprocessing def worker(d,l): l += range(15,21) for i in xrange(1,6): key = "key{0}".format(i) val = "val{0}".format(i) d[key] = val if __name__ == "__mian__": manager = multiprocessing.Manager() d = manager.dict() l = manager.list() p = multiprocessing.Process(target=worker,args=(d,l)) p.start() p.join() print(d) print(l) print("main end")2.进程池管理
#!/usr/bin/env python # -*- coding:utf8 -*- # @Time : 2017/12/12 16:29 # @Author : hantong # @File : process_5.py import multiprocessing import time def worker(msg): print("#######start {0}##########".format(msg)) time.sleep(1) print("#######end {0}##########".format(msg)) if __name__ == "__main__": pool = multiprocessing.Pool(processes=3) for i in xrange(1,10): msg = "hello {0}".format(i) pool.apply_async(func=worker,args=(msg,)) pool.close() pool.join() #在join之前一定要调用close,否则报错 print("end main")执行结果:
#######start hello 1##########
#######start hello 2##########
#######start hello 3##########
#######end hello 1##########
#######start hello 4##########
#######end hello 2##########
#######start hello 5##########
#######end hello 3##########
#######start hello 6##########
#######end hello 4##########
#######start hello 7##########
#######end hello 5##########
#######start hello 8##########
#######end hello 6##########
#######start hello 9##########
#######end hello 7##########
#######end hello 8##########
#######end hello 9##########
end main