How to terminate threads in a thread pool using Python?
To terminate threads in a thread pool, you can utilize the shutdown() method of the ThreadPoolExecutor class.
Below is an example showing how to create a thread pool using ThreadPoolExecutor and terminate threads when needed.
from concurrent.futures import ThreadPoolExecutor
import time
def task():
print("Thread started")
time.sleep(5)
print("Thread finished")
# 创建线程池
executor = ThreadPoolExecutor(max_workers=5)
# 提交任务到线程池
executor.submit(task)
# 终止线程池中的线程
executor.shutdown()
In the example above, a thread pool with a maximum of 5 threads was created using ThreadPoolExecutor. A task was then submitted to the thread pool using the submit() method. Finally, the shutdown() method was called to terminate the threads in the thread pool.
It is important to note that the shutdown() method will wait for all submitted tasks to be completed before terminating the threads in the thread pool. If you want to immediately terminate the threads in the thread pool, you can use the shutdown_now() method.
# 立即终止线程池中的线程
executor.shutdown_now()
It is important to note that using the shutdown_now() method to terminate threads in a thread pool may result in unfinished tasks being canceled.