【发布时间】:2013-03-06 07:07:15
【问题描述】:
当我试图终止一个运行在单独线程上的长时间运行的进程时,我遇到了问题。
以下是程序。 WorkOne 创建一个子进程并运行一个长时间运行的进程“adb logcat”,该进程会生成日志行。我在 main() 中启动 WorkOne,等待 5 秒并尝试停止它。多次运行给出多个输出
import threading
import time
import subprocess
import sys
class WorkOne(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
self.event = threading.Event()
self.process = subprocess.Popen(['adb','logcat'], stdout=subprocess.PIPE, stderr=sys.stdout.fileno())
def run(self):
for line in iter(self.process.stdout.readline,''):
#print line
if self.event.is_set():
self.process.terminate()
self.process.kill()
break;
print 'exited For'
def stop(self):
self.event.set()
def main():
print 'starting worker1'
worker1 = WorkOne()
worker1.start()
print 'number of threads: ' + str(threading.active_count())
time.sleep(5)
worker1.stop()
worker1.join(5)
print 'number of threads: ' + str(threading.active_count())
if __name__ == '__main__':
main()
有时我会得到 [A]:
starting worker1
number of threads: 2
number of threads: 2
exited For
有时我会得到 [B]:
starting worker1
number of threads: 2
number of threads: 1
exited For
有时我会得到 [C]:
starting worker1
number of threads: 2
number of threads: 2
我想我应该一直期望得到 [B]。这里出了什么问题?
【问题讨论】:
-
由于您在
join()调用中设置了超时,因此即使线程已停止,它也可能保持活动状态(例如,它正在等待for循环中的新行) . -
看起来这就是问题所在,将终止和终止调用从 for 循环中移至停止方法,现在我得到了我期望的一致输出
标签: python multithreading subprocess terminate long-running-processes