python's threading has no "interrupt"?

MetalOne jcb at iteris.com
Thu Dec 4 01:48:28 EST 2003


You might be able to solve your problem a couple of ways.
A sample scenario might be than you are using
a condition variable and are blocked in
cv.wait().  The user selects "exit" from a menu and you would like to
interrupt the cv.wait() so that the program may exit.

while not cond():
    cv.wait()
processData()

These lines of code require another thread to modify the condition and
call cv.notifyAll()

The cond() function could be modified
def cond():
    return origCond() and exitSelected


Alternatively a semaphore could be used.
s = Semaphore(2)
on startup
s.acquire()  #This one will be released upon selecting "exit".

later on
s.acquire() #This consumes a slot and continues or waits for an
available slot.
processData()

on "exit" calling s.release() will wake up the above code.

Finally, since both of these ideas may be a bit of a headache you
might find
setting Thread.setDaemon(True) to be useful.  This allows your program
to terminate when the main thread terminates even if other threads are
running.




More information about the Python-list mailing list