Python线程问题,raw_input()阻塞线程,失控线程

时间:2014-08-06 19:34:19

标签: python python-2.7 python-multithreading

我在python中遇到线程问题,问题似乎是当我调用一个线程后,调用raw_input()会阻塞该线程。这是最小的例子

import threading
import time

class tread_test(threading.Thread):
    def __init__(self):
        self.running = True
        threading.Thread.__init__(self)
    #

    def run(self):
        self.foo()
    #

    def foo(self):
        print "Spam, Spam, Spam"
        self.task = threading.Timer(0.5, self.foo)
        self.task.start()
    #

    def stop(self):
        self.running = False
        self.task.cancel()
    #
#

if __name__ == "__main__":
    a = tread_test()
    print "Starting now"
    a.start()
    raw_input()
    a.stop()
    print "Stopping now"

我对此的期望是:

Starting now
Spam, Spam, Spam
Spam, Spam, Spam
Spam, Spam, Spam
** user hits enter **
Stopping now

这是给我的:

>>> 
Starting now
Spam, Spam, Spam

** After several seconds user hits enter **

Traceback (most recent call last):
  File "C:\file\test.py", line 37, in <module>
    a.stop()
  File "C:\file\test.py", line 28, in stop
    self.task.cancel()
AttributeError: 'tread_test' object has no attribute 'task'
>>> Spam, Spam, Spam
Spam, Spam, Spam
Spam, Spam, Spam
Spam, Spam, Spam
Spam, Spam, Spam
Spam, Spam, Spam
Spam, Spam, Spam
================================ RESTART ================================

在重新启动终端之前,它一直打印出来。当我用threading.sleep()替换raw_input()命令暂停一段时间时,它按预期工作。在我看来,raw_input()以某种方式阻止foo()中的Timer执行。

为什么这不像我期望的那样工作?是因为某些原因它应该像这样工作,还是我错过了什么?

任何帮助将不胜感激。谢谢!

1 个答案:

答案 0 :(得分:4)

您的代码看起来很好,适用于Linux和Windows。我认为你遇到了IDLE解释器的限制,它往往会出现基于multiprocessingthreading的代码问题。我只是建议不要尝试从IDLE中运行代码。