views:

346

answers:

4

I am doing something like this in python

class MyThread ( threading.Thread ):
    def run (s):
        try:
            s.wantQuit = 0
            while(not s.wantQuit):
                button = raw_input()
                if button == "q":
                    s.wantQuit=1
        except KeyboardInterrupt:
            s.wantQuit = 1

myThread = MyThread ()
myThread.start()

a=5
while not myThread.wantQuit:
    print "hey"
    if (a == 0):
        break;
    a = a-1;
    time.sleep(1)
#"""
sys.exit()

What happens is my app locks up for 5 seconds printing "hey" (5 times) THEN i get the raw_input dialog. How can i have the dialog show up so i can quit anytime instead of when my loop runs out?

A: 

just tried the code to make sure, but this does do what it's supposed to... you can type q and enter in to the console and make the application quit before a=0 (so it says hey less then 5 times)

I don't know what you mean by the raw_input dialog, raw_input normally just takes info from stdin

Michael Walts
+1  A: 

You mean the while loop runs before the thread? Well, you can't predict this unless you synchronize it. No one guarantees you that the thread will run before or after that while loop. But if it's being blocked for 5 seconds that's akward - the thread should have been pre-empted by then.

Also, since you're first use of wantToQuit is in the run() method, no one assures you that the thread has been started when you're checking for it's wantToQuit attribute in while not myThread.wantToQuit .

hyperboreean
+1  A: 

The behaviour here is not what you described. Look at those sample outputs I got:

1st: pressing q<ENTER> as fast as possible:

hey
q

2nd: wait a bit before pressing q<ENTER>:

hey
hey
hey
q

3rd: Don't touch the keyboard:

hey
hey
hey
hey
hey
hey
# Application locks because main thread is over but 
# there are other threads running. add myThread.wantQuit = 1
# to prevent that if you want
nosklo
A: 

huperboreean has your answer. The thread is still being started when the for loop is executed.

You want to check that a thread is started before moving into your loop. You could simplify the thread to monitor raw_input, and return when a 'q' is entered. This will kill the thread.

You main for loop can check if the thread is alive.

jcoon