Python线程池代码实例
时间: 2023-10-26 08:15:52 浏览: 79
好的,以下是一个Python线程池的代码实例:
```python
import concurrent.futures
import time
def task(n):
print(f"Task {n} is starting...")
time.sleep(2)
print(f"Task {n} is ending...")
return f"Task {n} is completed!"
if __name__ == "__main__":
start_time = time.perf_counter()
with concurrent.futures.ThreadPoolExecutor(max_workers=3) as executor:
results = [executor.submit(task, i) for i in range(5)]
for future in concurrent.futures.as_completed(results):
print(future.result())
end_time = time.perf_counter()
print(f"Total execution time: {end_time - start_time:.2f} seconds.")
```
这段代码会创建一个最大线程数为3的线程池,然后提交5个任务给线程池进行处理。每个任务都会sleep 2秒来模拟耗时操作,然后返回一个字符串表示任务完成。最后,代码会输出每个任务的返回结果,并计算总共的执行时间。注意,我们使用`concurrent.futures`模块来实现线程池的操作。
阅读全文