线程池的基类是 concurrent.futures 模块中的 Executor,Executor 提供了两个子类,即 ThreadPoolExecutor 和 ProcessPoolExecutor,其中 ThreadPoolExecutor 用于创建线程池,而 ProcessPoolExecutor 用于创建进程池。
示例代码1: 【使用map方法】
from concurrent.futures import ThreadPoolExecutor, TimeoutError
import time
def tasks(num):
count = 0
for i in range(num):
count += i
time.sleep(0.1)
return f"total:{count}"
# 创建一个包含4个线程的线程池,使用map函数
def thread_pool_run():
with ThreadPoolExecutor(max_workers=4) as pool:
# 后面元组有3个元素,因此程序启动3条线程来执行tasks函数
results = pool.map(tasks, [10, 20, 30])
for i in results:
print(i)
if __name__ == '__main__':
thread_pool_run()
运行结果:
示例代码2:
from concurrent.futures import ThreadPoolExecutor, TimeoutError
import time
def tasks(num):
count = 0
for i in range(num):
count += i
time.sleep(0.1)
return f"total:{count}"
# 创建一个包含4个线程的线程池,使用map函数
def thread_pool_run():
with ThreadPoolExecutor(max_workers=4) as pool:
# 后面元组有3个元素,因此程序启动3条线程来执行tasks函数
results = pool.map(tasks, [10, 20, 30])
for i in results:
print(i)
# 设置线程超时
def thread_pool_set_timeout():
futures = []
with ThreadPoolExecutor(max_workers=4) as pool:
for i in (10, 20, 30, 40, 50):
future = pool.submit(tasks, i)
futures.append([i, future])
for future in futures:
try:
res = future[1].result(timeout=2)
print(res)
except TimeoutError:
print(future[0], ': is timeout!')
if __name__ == '__main__':
# thread_pool_run()
thread_pool_set_timeout()
运行结果: