![](/img/trans.png)
[英]Killing QThread and multiprocessing.pool Processes in Long Running Task
[英]python multiprocessing.Pool kill *specific* long running or hung process
我需要执行许多并行数据库连接和查询的池。 我想使用multiprocessing.Pool或concurrent.futures ProcessPoolExecutor。 Python 2.7.5
在某些情况下,查询请求需要太长时间或永远不会完成(挂起/僵尸进程)。 我想从已经超时的multiprocessing.Pool或concurrent.futures ProcessPoolExecutor中删除特定进程。
下面是一个如何杀死/重新生成整个进程池的示例,但理想情况下我会尽量减少CPU抖动,因为我只想杀死在超时秒后没有返回数据的特定长时间运行进程。
出于某种原因,在返回并完成所有结果后,下面的代码似乎无法终止/加入进程池。 它可能与发生超时时杀死工作进程有关,但是当Pool被杀死并且结果符合预期时,Pool会创建新工作程序。
from multiprocessing import Pool
import time
import numpy as np
from threading import Timer
import thread, time, sys
def f(x):
time.sleep(x)
return x
if __name__ == '__main__':
pool = Pool(processes=4, maxtasksperchild=4)
results = [(x, pool.apply_async(f, (x,))) for x in np.random.randint(10, size=10).tolist()]
while results:
try:
x, result = results.pop(0)
start = time.time()
print result.get(timeout=5), '%d done in %f Seconds!' % (x, time.time()-start)
except Exception as e:
print str(e)
print '%d Timeout Exception! in %f' % (x, time.time()-start)
for p in pool._pool:
if p.exitcode is None:
p.terminate()
pool.terminate()
pool.join()
我不完全理解你的问题。 您说您想要停止一个特定的进程,但是,在您的异常处理阶段,您正在调用所有作业的终止。 不知道你为什么这样做。 此外,我很确定使用multiprocessing.Pool
内部变量multiprocessing.Pool
不太安全。 说完所有这些之后,我认为你的问题是为什么当超时发生时这个程序没有完成。 如果这是问题,那么以下是诀窍:
from multiprocessing import Pool
import time
import numpy as np
from threading import Timer
import thread, time, sys
def f(x):
time.sleep(x)
return x
if __name__ == '__main__':
pool = Pool(processes=4, maxtasksperchild=4)
results = [(x, pool.apply_async(f, (x,))) for x in np.random.randint(10, size=10).tolist()]
result = None
start = time.time()
while results:
try:
x, result = results.pop(0)
print result.get(timeout=5), '%d done in %f Seconds!' % (x, time.time()-start)
except Exception as e:
print str(e)
print '%d Timeout Exception! in %f' % (x, time.time()-start)
for i in reversed(range(len(pool._pool))):
p = pool._pool[i]
if p.exitcode is None:
p.terminate()
del pool._pool[i]
pool.terminate()
pool.join()
关键是你需要从池中删除项目; 只是在他们身上调用终止是不够的。
要避免访问内部变量,可以将执行任务中的multiprocessing.current_process().pid
保存到共享内存中。 然后从主进程迭代multiprocessing.active_children()
并杀死目标pid
如果存在)。
但是,在这些外部终止工作程序之后,它们会被重新创建,但是池变得不可连接,并且还需要在join()
之前显式终止
我也遇到过这个问题。
@stacksia的原始代码和编辑版本具有相同的问题:在两种情况下,当只有一个进程达到超时时(即当完成pool._pool
上的循环时), pool._pool
所有当前正在运行的进程。
找到我的解决方案。 它涉及为.pid
建议的每个工作进程创建一个.pid
文件。 如果有标记每个工作进程的方法,它将起作用(在下面的代码中, x
执行此工作)。 如果某人有更优雅的解决方案(例如在内存中保存PID),请分享。
#!/usr/bin/env python
from multiprocessing import Pool
import time, os
import subprocess
def f(x):
PID = os.getpid()
print 'Started:', x, 'PID=', PID
pidfile = "/tmp/PoolWorker_"+str(x)+".pid"
if os.path.isfile(pidfile):
print "%s already exists, exiting" % pidfile
sys.exit()
file(pidfile, 'w').write(str(PID))
# Do the work here
time.sleep(x*x)
# Delete the PID file
os.remove(pidfile)
return x*x
if __name__ == '__main__':
pool = Pool(processes=3, maxtasksperchild=4)
results = [(x, pool.apply_async(f, (x,))) for x in [1,2,3,4,5,6]]
pool.close()
while results:
print results
try:
x, result = results.pop(0)
start = time.time()
print result.get(timeout=3), '%d done in %f Seconds!' % (x, time.time()-start)
except Exception as e:
print str(e)
print '%d Timeout Exception! in %f' % (x, time.time()-start)
# We know which process gave us an exception: it is "x", so let's kill it!
# First, let's get the PID of that process:
pidfile = '/tmp/PoolWorker_'+str(x)+'.pid'
PID = None
if os.path.isfile(pidfile):
PID = str(open(pidfile).read())
print x, 'pidfile=',pidfile, 'PID=', PID
# Now, let's check if there is indeed such process runing:
for p in pool._pool:
print p, p.pid
if str(p.pid)==PID:
print 'Found it still running!', p, p.pid, p.is_alive(), p.exitcode
# We can also double-check how long it's been running with system 'ps' command:"
tt = str(subprocess.check_output('ps -p "'+str(p.pid)+'" o etimes=', shell=True)).strip()
print 'Run time from OS (may be way off the real time..) = ', tt
# Now, KILL the m*$@r:
p.terminate()
pool._pool.remove(p)
pool._repopulate_pool()
# Let's not forget to remove the pidfile
os.remove(pidfile)
break
pool.terminate()
pool.join()
很多人建议鹅卵石。 它看起来很不错,但只适用于Python 3.如果有人有办法为python 2.6导入pebble - 会很棒。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.