python 之 线程池实现并发

使用线程池实现高IO并发

模块:ThreadPoolExecutor, as_completed

测试代码如下:

#!/opt/python3/bin/python3

from concurrent.futures import ThreadPoolExecutor, as_completed
import time

def test(arg1, arg2, arg3):
    time.sleep(int(arg1))
    print('参数1:%s 参数2:%s 参数3:%s' % (arg1,arg2,arg3))
    return arg1


# 创建含3个线程的线程池
with ThreadPoolExecutor(3) as executor:
    # 生成所有任务
    all_task = [executor.submit(test, ag1, ag2, ag3) for ag1, ag2, ag3 in [('2','aa1','aa2'),('3','bb1','bb2')]]

# 等待任务全部执行完毕后,使用for的result方法循环返回结果
for out in as_completed(result):
    mess = out.result()
    print(mess)

# as_completed 方法是等待result任务全部执行完毕
# result 方法是提取任务返回的结果

  

猜你喜欢

转载自www.cnblogs.com/zy6103/p/10963445.html