from concurrent.futures import ThreadPoolExecutor
import time
def say_hello(a, s):
print("hello: "+a)
print(s)
time.sleep(4)
return {"code": 111}
def main():
seed=["a","b","c", "d"]
start2=time.time()
future = {}
# 创建包含3个线程的线程池
executor = ThreadPoolExecutor(3)
for each in seed:
# 提交任务到线程池
a = executor.submit(say_hello, each, 4)
# 保存提交后返回的对象用来查询结果(A Future representing the given call)
future[each] = a
# shutdown用来保证不会在向线程池中新增任务,其内参数为False表示不会等待线程池内任务结束,直接返回(常用于不需要返回结果时),参数为True时(默认为True),会等待线程池内任务执行完毕才会继续向下走
executor.shutdown(False)
# 当使用future["a"].result()时,无论shutdown内参数是True还是False,都会阻塞至直到该任务执行完.
# result()内的数字为超时时间,单位是s,默认值为None,无超时时间
print(future["a"].result(5))
end2=time.time()
print("time2: "+str(end2-start2))
return
if __name__ == '__main__':
main()
python的线程池使用
最新推荐文章于 2024-09-17 08:29:36 发布