2

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!

3
  • Hmm, it's working fine for me on both Windows and Linux. What environment are you trying to run the script in? Commented Aug 6, 2014 at 19:41
  • IDLE shell on Windows 7 under python 2.7 Commented Aug 6, 2014 at 20:12
  • I tried it in a standard python shell in windows and it works as expected. It would seem that the bug is specific to IDLE. Commented Aug 6, 2014 at 20:20

1 Answer 1

5

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.