我一直在尝试为控制某些硬件的库编写一个交互式包装器(用于ipython).有些调用对IO很重要,因此并行执行任务是有意义的.使用ThreadPool(几乎)很好地工作:
from multiprocessing.pool import ThreadPool
class hardware():
def __init__(IPaddress):
connect_to_hardware(IPaddress)
def some_long_task_to_hardware(wtime):
wait(wtime)
result = 'blah'
return result
pool = ThreadPool(processes=4)
Threads=[]
h=[hardware(IP1),hardware(IP2),hardware(IP3),hardware(IP4)]
for tt in range(4):
task=pool.apply_async(h[tt].some_long_task_to_hardware,(1000))
threads.append(task)
alive = [True]*4
Try:
while any(alive) :
for tt in range(4): alive[tt] = not threads[tt].ready()
do_other_stuff_for_a_bit()
except:
#some command I cannot find that will stop the threads...
raise
for tt in range(4): print(threads[tt].get())
Run Code Online (Sandbox Code Playgroud)
如果用户想要停止进程或者出现IO错误,则会出现问题do_other_stuff_for_a_bit().按Ctrl+ C停止主进程,但工作线程继续运行,直到当前任务完成.
有没有办法阻止这些线程,而不必重写库或让用户退出python? pool.terminate()而pool.join()我在其他例子中看到的似乎并没有做到这一点.
实际例程(而不是上面的简化版本)使用日志记录,虽然所有工作线程都在某个时刻关闭,但我可以看到它们开始运行的进程一直持续到完成(并且硬件我可以通过查看看到它们的效果穿过房间).
这是在python 2.7中.
更新:
解决方案似乎是切换到使用multiprocessing.Process而不是线程池.我试过的测试代码是运行foo_pulse:
class …Run Code Online (Sandbox Code Playgroud)