奇怪的线程行为

2024-10-02 12:30:02 发布

您现在位置:Python中文网/ 问答频道 /正文

我对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。怎么会这样?你知道吗


Tags: self程序falseoutputinitdefstdoutprocess
3条回答

tito's answer为基础,关于您的评论,您可以在select.select中使用超时:

    while (not self.isStopping):
        ready, _, _ = select.select([p.stdout], [], [], 5.0)

        # Don't process the last output if we are stopping
        if (self.isStopping):
            print 'Quitting, discarding last buffer:' + str(self.isStopping)
            continue
        if ready:
            # do some p.stdout.readline() and process the data

    self.ioprocess.terminate()

以上,超时为5.0秒。我认为这足够长,不足以打击系统,足够短,可以合理终止。改变以适合你的口味。你知道吗

如果在线程外调用stop(),可能会导致随机问题。因为当您调用stop()时,线程可以是打印或选择等

只需将terminate()移动到run()方法末尾的terminate()。然后将isStopping设置为True将正确地离开循环,然后终止进程。你知道吗

如果要等待,可以使用以下方法加入线程:

def stop(self):
    self.isStopping = True
    self.join()

如果目标是在应用程序结束时结束线程,那么将线程设置为守护进程。你知道吗

相关问题 更多 >

    热门问题