import time from multiprocessing import Pool #Pool中的P要大写的 deftest1(): time.sleep(1) for i inrange(10): print('test1',i) deftest2(): time.sleep(1) for i inrange(10): print('test2',i) if __name__ == '__main__': pool = Pool(5) #Pool的默认大小是CPU的核数,进程数可以手动更改 pool.apply_async(test1) pool.apply_async(test2) pool.close() pool.join() #调用join()方法会等待所有子进程执行完毕,调用join()之前必须先调用close(),调用close()之后就不能继续添加新的process了。
from multiprocessing import Process, Queue import os, time, random
# 写数据进程执行的代码: defwrite(q): print('Process to write: %s' % os.getpid()) for value in ['A','B','C']: print('Put %s to queue...' % value) q.put(value) time.sleep(random.random()) # 读数据进程执行的代码: defread(q): print('Process to read: %s' % os.getpid()) whileTrue: value = q.get(True) print('Get %s from queue.' % value) 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进程里是死循环,无法等待其结束,只能强行终止: pr.terminate()
运行结果:
1 2 3 4 5 6 7 8
Process to write: 2024 Put A to queue... Process to read: 4308 Get A from queue. Put B to queue... Get B from queue. Put C to queue... Get C from queue.