Reputation: 554
I'm having an issue with threading in python, the issue seems to be that when I call a thread subsequently calling raw_input() blocks the thread. Here is the minimal example
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"
What I expect from this is:
Starting now
Spam, Spam, Spam
Spam, Spam, Spam
Spam, Spam, Spam
** user hits enter **
Stopping now
Here is what this gives me:
>>>
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 ================================
Where it keeps printing out until I restart the terminal. When I replace the raw_input() command with threading.sleep() to pause for some amount of time it works as expected. It seems to me that raw_input() is somehow blocking the Timer in foo() from executing.
Why isn't this working as I expect? Is it supposed to work like this for some reason, or am I missing something?
Any help would be appreciated. Thanks!
Upvotes: 2
Views: 1713
Reputation: 94881
Your code looks fine, and works for me on both Linux and Windows. I think you're running into a limitation of IDLE's interpreter, which tends to have issues with both multiprocessing
and threading
-based code. I would simply recommend not trying to run your code from within IDLE.
Upvotes: 5