concurrent.futures

 

import os
import sys
import time
from threading import Thread
from multiprocessing import Process
from concurrent.futures import ThreadPoolExecutor, ProcessPoolExecutor

# t = ThreadPoolExecutor(os.cpu_count())
# p = ProcessPoolExecutor(os.cpu_count())
executor = ProcessPoolExecutor(max_workers=os.cpu_count())


def foo(a, b):
    time.sleep(1)
    print(f"foo end: {a}{b}...")
    return a, b


def boo(obj):
    res = obj.result()
    print(f"boo.. {res}")


if __name__ == '__main__':
    start_time = time.time()
    for i in range(3):
        res = executor.submit(foo, "Elton", i)
        print(res.done())  # 是否执行完成
        res.add_done_callback(boo) # 添加回调函数
    print("主进程")
    end_time = time.time()
    print(f"Time consuming {end_time - start_time}")

"""

False
False
False
主进程
Time consuming 0.013116836547851562
foo end: Elton1...
foo end: Elton0...
boo.. ('Elton', 0)
foo end: Elton2...
boo.. ('Elton', 1)
boo.. ('Elton', 2)

"""

 

posted @ 2020-07-22 00:38  Elton丶  阅读(110)  评论(0编辑  收藏  举报