1.1 多进程技术
多进程模块的使用与多线程的模块使用基本类似,修改上面的例子,仅仅将threading改为multiprocessing即可。
from time import sleep, ctime import multiprocessing def player(file, time): #播放器 for i in range(2): print('Starting playing: %s! %s' % (file, ctime())) sleep(time) #播放列表及时长 lists = {'以后的以后':3,'One Day':2,'阿甘正传':4} #创建线程组 threads = [] for file,time in lists.items(): t = multiprocessing.Process(target=player, args =(file,time)) threads.append(t) if __name__ == '__main__': for t in range(len(lists)): threads[t].start() for t in range(len(lists)): threads[t].join() print('all end: %s' % ctime())
执行结果
Starting playing: 以后的以后! Mon May 21 17:24:02 2018 Starting playing: One Day! Mon May 21 17:24:02 2018 Starting playing: 阿甘正传! Mon May 21 17:24:02 2018 Starting playing: One Day! Mon May 21 17:24:04 2018 Starting playing: 以后的以后! Mon May 21 17:24:05 2018 Starting playing: 阿甘正传! Mon May 21 17:24:06 2018 all end: Mon May 21 17:24:10 2018 Process finished with exit code 0
multiprocessing.Process(group=None, target=None, name=None, arge=(), kwargs={})
target表示调用的对象,args表示调用对象的位置参数元组,kwargs表示调用对象的字典,name为别名,Group实际上不适用。