【发布时间】:2017-10-27 23:14:58
【问题描述】:
我正在使用 Ubuntu 16.04.2 LTS 和 Python 3.5.2。
我有一个来自multiprocessing 的ThreadPool 正在做一些工作。
现在我想在工作时终止这个池。
使用ThreadPool.terminate() 无法按预期工作。
运行以下示例时,worker 永远不会停止工作,并且程序永远不会超过 ThreadPool.join() 调用。
import time
from multiprocessing.pool import ThreadPool
def task():
try:
while True:
print("Working")
time.sleep(1)
except: # Unsuccessful attempt. :(
print("Working, stopping now")
thread_pool = ThreadPool(processes=1)
thread_pool.apply_async(task)
time.sleep(1) # Make sure the task is actually started.
print("Terminating")
thread_pool.terminate()
print("Termination: Initiated")
thread_pool.join() # Does not return.
print("Termination: Done")
我做错了什么?
【问题讨论】:
标签: python multithreading python-3.x python-multiprocessing python-multithreading