[Tips] python 多进行使用
快速实现
1. 同一个函数不同的输入数据
from multiprocessing import Pool import os, time, random def task1(name): print('Run task %s (%s)...' % (name, os.getpid())) start = time.time() time.sleep(random.random() * 3) end = time.time() print('Task %s runs %0.2f seconds.' % (name, (end - start))) if __name__=='__main__': print('Parent process %s.' % os.getpid()) p = Pool(4) for i in range(5): p.apply_async(task1, args=(i,)) print('Waiting for all subprocesses done...') p.close() p.join() print('All subprocesses done.')
或者采用pool的map函数,但是注意这个返回的结果顺序和输入的i_list并不一致:
#coding: utf-8 import multiprocessing def m1(x): return x * x if __name__ == '__main__': pool = multiprocessing.Pool(multiprocessing.cpu_count()) i_list = range(8) results = pool.map(m1, i_list)
print(results)