# -*- coding: utf-8 -*-
import time
from concurrent.futures import ThreadPoolExecutor, as_completed
def fib(n):
if n < 3:
return 1
return fib(n-1) + fib(n-2)
start_time = time.time()
executor = ThreadPoolExecutor(max_workers=4)
task_list = [executor.submit(fib, n) for n in range(3,35)]
thread_results = [task.result() for task in as_completed(task_list)]
print(thread_results)
print("ThreadPoolExecutor time is: {}".format(time.time() - start_time))
输出结果:
[3, 8, 5, 2, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584,
4181, 6765, 10946, 28657, 17711, 46368, 75025, 121393,
196418, 317811, 514229, 832040, 1346269, 2178309, 3524578, 5702887]
ThreadPoolExecutor time is: 1.7373127937316895
总结
1 future的设计理念很棒,在线程池/进程池和携程中都存在future对象,是异步编程的核心。
2 ThreadPoolExecutor 让线程的使用更加方便,减小了线程创建/销毁的资源损耗,无需考虑线程间的复杂同步,方便主线程与子线程的交互。
3 线程池的抽象程度很高,多线程和多进程的编码接口一致。