# 提交任务的两种方式
# 1.同步调用:调用任务后, 原地等待任务执行完毕,
# 导致程序串行执行
import time, random
from concurrent.futures import ThreadPoolExecutor
def la(name):
print('%s is pooping' % name)
time.sleep(random.randint(3, 5))
res = random.randint(7, 13) * '#'
return {'name': name, 'res': res}
def weight(crap): #crap 是一个 Futures 对象
crap = crap.result()
name = crap['name']
size = len(crap['res'])
print('%s pooped [%s] kg' % (name, size))
# if __name__ == '__main__':
# pool = ThreadPoolExecutor(12)
# start = time.time()
# for i in range(133):
# crap = pool.submit(la, 'member-%s' % i).result()
# weight(crap)
# stop = time.time()
# print(stop - start) # 500s
# 2.异步调用:调用任务后, 不等待,任务执行随意,
# 程序并行执行
if __name__ == '__main__':
pool = ThreadPoolExecutor(12)
start = time.time()
for i in range(133):
p = pool.submit(la, 'member-%s' % i)
p.add_done_callback(weight)
pool.shutdown()
stop = time.time()
print(stop - start) # 46s