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的線程池使用
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.