我一直在尝试为控制某些硬件的库编写一个交互式包装器(用于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())
如果用户想要停止该过程或do_other_stuff_for_a_bit()
中存在IO错误,则会出现问题。按 Ctrl + C 将停止主进程,但工作线程继续运行,直到当前任务完成为止。
有没有办法阻止这些线程,而不必重写库或让用户退出python?我在其他示例中看到的pool.terminate()
和pool.join()
似乎没有做到这一点。
实际例程(而不是上面的简化版本)使用日志记录,虽然所有工作线程都在某个时刻关闭,但我可以看到他们开始运行的进程一直持续到完成(并且是硬件,我可以看到他们的通过看房间的效果)。
这是在python 2.7中。
更新
解决方案似乎是切换到使用multiprocessing.Process而不是线程池。我尝试的测试代码是运行foo_pulse:
class foo(object):
def foo_pulse(self,nPulse,name): #just one method of *many*
print('starting pulse for '+name)
result=[]
for ii in range(nPulse):
print('on for '+name)
time.sleep(2)
print('off for '+name)
time.sleep(2)
result.append(ii)
return result,name
如果你尝试使用ThreadPool运行它,那么ctrl-C不会阻止foo_pulse运行(即使它确实会立即终止线程,打印语句仍在继续:
from multiprocessing.pool import ThreadPool
import time
def test(nPulse):
a=foo()
pool=ThreadPool(processes=4)
threads=[]
for rn in range(4) :
r=pool.apply_async(a.foo_pulse,(nPulse,'loop '+str(rn)))
threads.append(r)
alive=[True]*4
try:
while any(alive) : #wait until all threads complete
for rn in range(4):
alive[rn] = not threads[rn].ready()
time.sleep(1)
except : #stop threads if user presses ctrl-c
print('trying to stop threads')
pool.terminate()
print('stopped threads') # this line prints but output from foo_pulse carried on.
raise
else :
for t in threads : print(t.get())
但是,使用multiprocessing.Process的版本按预期工作:
import multiprocessing as mp
import time
def test_pro(nPulse):
pros=[]
ans=[]
a=foo()
for rn in range(4) :
q=mp.Queue()
ans.append(q)
r=mp.Process(target=wrapper,args=(a,"foo_pulse",q),kwargs={'args':(nPulse,'loop '+str(rn))})
r.start()
pros.append(r)
try:
for p in pros : p.join()
print('all done')
except : #stop threads if user stops findRes
print('trying to stop threads')
for p in pros : p.terminate()
print('stopped threads')
else :
print('output here')
for q in ans :
print(q.get())
print('exit time')
我为库foo定义了一个包装器(因此不需要重写)。如果不需要返回值,则此包装器都不是:
def wrapper(a,target,q,args=(),kwargs={}):
'''Used when return value is wanted'''
q.put(getattr(a,target)(*args,**kwargs))
从文档中我看不出池无法工作的原因(除了bug)。
答案 0 :(得分:2)
这是对并行性的非常有趣的用法。
但是,如果您使用的是multiprocessing
,那么目标是让许多进程并行运行,而不是运行多个线程的进程。
考虑使用multiprocessing
实现它的一些更改:
你有这些并行运行的功能:
import time
import multiprocessing as mp
def some_long_task_from_library(wtime):
time.sleep(wtime)
class MyException(Exception): pass
def do_other_stuff_for_a_bit():
time.sleep(5)
raise MyException("Something Happened...")
让我们创建并启动流程,比如4:
procs = [] # this is not a Pool, it is just a way to handle the
# processes instead of calling them p1, p2, p3, p4...
for _ in range(4):
p = mp.Process(target=some_long_task_from_library, args=(1000,))
p.start()
procs.append(p)
mp.active_children() # this joins all the started processes, and runs them.
进程并行运行,可能是在一个单独的cpu核心中运行,但这是由操作系统来决定的。您可以签入系统监视器。
与此同时,你运行一个会中断的进程,并且你想要停止正在运行的进程,而不是让他们离开orphan:
try:
do_other_stuff_for_a_bit()
except MyException as exc:
print(exc)
print("Now stopping all processes...")
for p in procs:
p.terminate()
print("The rest of the process will continue")
如果在一个或所有子进程终止时继续主进程没有意义,则应该处理主程序的退出。
希望它有所帮助,你可以为你的图书馆调整一些。
答案 1 :(得分:0)
在回答为什么池不起作用的问题时,这是由于(在Documentation中引用),然后 main 需要由子进程导入,并且由于正在使用这个项目交互式python的本质。
同时不清楚为什么ThreadPool会 - 虽然线索就在名称中。 ThreadPool使用multiprocessing.dummy创建其工作进程池,如上所述here只是Threading模块的包装器。 Pool使用multiprocessing.Process。这可以通过这个测试看出:
p=ThreadPool(processes=3)
p._pool[0]
<DummyProcess(Thread23, started daemon 12345)> #no terminate() method
p=Pool(processes=3)
p._pool[0]
<Process(PoolWorker-1, started daemon)> #has handy terminate() method if needed
由于线程没有terminate方法,工作线程继续运行直到它们完成当前任务。杀死线程很乱(这就是我尝试使用多处理模块的原因),但解决方案是here。
关于使用上述解决方案的一个警告:
def wrapper(a,target,q,args=(),kwargs={}):
'''Used when return value is wanted'''
q.put(getattr(a,target)(*args,**kwargs))
是对象实例内的属性更改不会传递回主程序。作为一个例子,上面的类foo也可以有如下方法:
def addIP(newIP):
self.hardwareIP = newIP
致r=mp.Process(target=a.addIP,args=(127.0.0.1))
的电话不会更新a
。
复杂对象的唯一解决方法似乎是使用自定义manager
的共享内存,它可以访问对象a
的方法和属性。对于一个非常大的复杂对象,基于最好使用dir(foo)
来填充经理。如果我能弄清楚如何用一个例子更新这个答案(对于我未来的自我和其他人一样)。
答案 2 :(得分:0)
如果出于某些原因最好使用线程,则可以使用this。
我们可以向要终止的线程发送一些信号。最简单的信号是全局变量:
import time
from multiprocessing.pool import ThreadPool
_FINISH = False
def hang():
while True:
if _FINISH:
break
print 'hanging..'
time.sleep(10)
def main():
global _FINISH
pool = ThreadPool(processes=1)
pool.apply_async(hang)
time.sleep(10)
_FINISH = True
pool.terminate()
pool.join()
print 'main process exiting..'
if __name__ == '__main__':
main()