python多任務編程-線程池-通過回調函數獲取返回值


示例代碼如下:

import threading
import time
from concurrent.futures import ThreadPoolExecutor


def make_food(food):
    print(food, "開始制作")
    time.sleep(2)
    print(food, "制作完成")
    return food


def get_finish_food(future):
    print(future.result())
    return future.result()


def main():

    food_list = ['番茄炒雞蛋', '青椒炒牛肉']
	
    # 創建2個線程
    pool = ThreadPoolExecutor(max_workers=2)

    for food in food_list:
        future = pool.submit(make_food, food)
        # 不阻塞,通過回調函數,獲取函數返回值
        future.add_done_callback(get_finish_food)


if __name__ == '__main__':
    main()


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM