concurrent.futures.ThreadPoolExecutor的用法
时间: 2023-07-25 15:23:54 浏览: 94
concurrent.futures.ThreadPoolExecutor是Python 3中的一个线程池模块,它可以用来管理和调度多个线程,从而实现并发执行任务的目的。ThreadPoolExecutor实现了Executor接口,提供了submit()方法来提交任务。
下面是ThreadPoolExecutor的用法示例:
```python
import concurrent.futures
import time
def worker(num):
print(f"Thread-{num} start")
time.sleep(1)
print(f"Thread-{num} end")
if __name__ == '__main__':
with concurrent.futures.ThreadPoolExecutor(max_workers=3) as executor:
for i in range(5):
executor.submit(worker, i)
```
在该示例中,我们定义了一个worker函数来模拟执行任务的过程,然后使用ThreadPoolExecutor创建一个最大工作线程数为3的线程池,通过submit()方法向线程池提交任务。
输出结果如下:
```
Thread-0 start
Thread-1 start
Thread-2 start
Thread-0 end
Thread-3 start
Thread-1 end
Thread-4 start
Thread-2 end
Thread-3 end
Thread-4 end
```
从输出结果中可以看出,线程池最多同时运行3个线程,第4个和第5个任务等待前面的任务执行完毕后才被执行。
阅读全文
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)