我对python比较陌生,但对多线程软件不太熟悉,所以我无法解释我看到的特定行为。我的程序非常简单:我监视linux命令iostat的输出,并在某些情况下执行一些操作。我的代码如下:
class SysMonitor(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
self.isStopping = False
self.ioprocess = []
def run(self):
self.ioprocess = subprocess.Popen(['/usr/bin/iostat', '-p', 'sda', '60'], stdout=subprocess.PIPE)
p = self.ioprocess
i = 0
# Discard first output
while (i < 11):
p.stdout.readline()
i = i + 1
# Now keep on waiting on new output from iostat and then process it when it comes in
while (not self.isStopping):
select.select([p.stdout], [], [])
# Don't process the last output if we are stopping
if (self.isStopping):
print 'Quitting, discarding last buffer:' + str(self.isStopping)
continue
# do some p.stdout.readline() and process the data
def stop(self):
self.isStopping = True
self.ioprocess.terminate()
我不明白的是,当我调用'stop'函数时,程序有时会崩溃,因为select被释放,因为EOF写在标准输出缓冲区中,但isStopping仍然是False。怎么会这样?你知道吗
以tito's answer为基础,关于您的评论,您可以在
select.select
中使用超时:以上,超时为5.0秒。我认为这足够长,不足以打击系统,足够短,可以合理终止。改变以适合你的口味。你知道吗
如果在线程外调用
stop()
,可能会导致随机问题。因为当您调用stop()时,线程可以是打印或选择等只需将
terminate()
移动到run()
方法末尾的terminate()
。然后将isStopping
设置为True将正确地离开循环,然后终止进程。你知道吗如果要等待,可以使用以下方法加入线程:
如果目标是在应用程序结束时结束线程,那么将线程设置为守护进程。你知道吗
相关问题 更多 >
编程相关推荐