#练习: import time from multiprocessing import Pool def run(fn): #fn: 函数参数是数据列表的一个元素 time.sleep(1) return fn * fn if __name__ == "__main__": testFL = [1,2,3,4,5,6] print 'Single process execution sequence:' #顺序执行(也就是串行执行,单进程) s = time.time() for fn in testFL: run(fn) e1 = time.time() print u"顺序执行时间:", int(e1 - s) print 'concurrent:' #创建多个进程,并行执行 pool = Pool(5) #创建拥有5个进程数量的进程池 #testFL:要处理的数据列表,run:处理testFL列表中数据的函数 rl =pool.map(run, testFL) pool.close()#关闭进程池,不再接受新的任务 pool.join()#主进程阻塞等待子进程的退出 e2 = time.time() print u"并行执行时间:", int(e2 - e1) print rl #练习: from multiprocessing import Process, Queue import os, time, random # 写数据进程执行的代码: def write(q): for value in ['A', 'B', 'C']: print 'Put %s to queue...' % value q.put(value) time.sleep(random.random()) # 读数据进程执行的代码 def read(q): time.sleep(1) while not q.empty(): # if not q.empty(): print 'Get %s from queue.' % q.get(True) time.sleep(1) # 目的是等待写队列完成 if __name__=='__main__': # 父进程创建Queue,并传给各个子进程 q = Queue() pw = Process(target = write, args = (q,)) pr = Process(target = read, args = (q,)) # 启动子进程pw,写入: pw.start() # 启动子进程pr,读取: pr.start() # 等待pw结束: pw.join() pr.join() print “Done!”