进程池与线程池(concurrent.futures)_Python开发进程池与线程池(concurrent.futures)_进程_02
 1 from concurrent.futures import ProcessPoolExecutor
 2 import os,time,random
 3 def task(n):
 4     print('%s is running'%os.getpid())
 5     time.sleep(random.randint(1,2))
 6     return n**2
 7 if __name__ == '__main__':
 8     p = ProcessPoolExecutor()     #默认开启四个进程池
 9     l = []
10     start = time.time()
11     for i in range(10):
12         obj = p.submit(task,i)
13         l.append(obj)
14     p.shutdown()
15     print('='*30)
16     print([obj for obj in l])
17     print(time.time() - start)
进程池
进程池与线程池(concurrent.futures)_Python开发进程池与线程池(concurrent.futures)_进程_02
 1 from concurrent.futures import ThreadPoolExecutor
 2 import threading
 3 import os,time,random
 4 def task(n):
 5     print('%s:%s is running'%(threading.currentThread().getName(),os.getpid()))
 6     time.sleep(random.randint(1,2))
 7     return n**2
 8 if __name__ == '__main__':
 9     t = ThreadPoolExecutor()
10     l = []
11     start = time.time()
12     for i in range(10):
13         obj = t.submit(task,i)
14         l.append(obj)
15     t.shutdown()
16     print('='*30)
17     print([obj.result() for obj in l])   #可以获取结果
18     print(time.time() - start)
线程池
进程池与线程池(concurrent.futures)_Python开发进程池与线程池(concurrent.futures)_进程_02
 1 from concurrent.futures import ProcessPoolExecutor
 2 import os,time,random
 3 def task(n):
 4     print('%s is running'%os.getpid())
 5     time.sleep(1)
 6     return n**2
 7 if __name__ == '__main__':
 8     p = ProcessPoolExecutor()
 9     start = time.time()
10     for i in range(10):
11         res = p.submit(task,i).result()    #同步执行,速度较慢,一个等一个
12         print(res)
13     print('='*30)
14     print(time.time() - start)
补充