我有一个简单的 Python 线程示例,如下所示:
class MyClass(object):
threads = 5
def run_in_threads(self, variable1_list, variable2):
with concurrent.futures.ThreadPoolExecutor(max_workers=threads) as executor:
pool = {executor.submit(self.run, variable1, variable2) for variable1 in variable1_list}
concurrent.futures.wait(pool)
def run(self, variable1, variable2):
t = SingleThread(scf_file_path, variable2)
t.start()
t.join()
class SingleThread(threading.Thread):
def __init__(self, variable1, variable2):
logger.debug("Single thread init.")
threading.Thread.__init__(self)
self.my_variable = my_variable
def run(self):
logger.debug("Single thread started.")
# command = my long methond, e.g. subprocess
p = subprocess.Popen(command)
p.wait()
logger.debug("Single thread ended.")
问题是有时子进程命令被卡住,然后整个进程停止(脚本的下一部分无法运行)。
能否请您验证这段代码并给出提示,如果时间达到限制,例如如何继续强制终止线程? 1分钟?
谢谢@shmee 的提示。在 subprocess.wait 方法中添加超时是最简单的解决方案:
def run(self):
logger.debug("Single thread started.")
# command = my long methond, e.g. subprocess
p = subprocess.Popen(command)
p.wait(timeout=60) # <===
logger.debug("Single thread ended.")
我是一名优秀的程序员,十分优秀!