Revision 4 as of 2002-08-12 14:07:57

Clear message

I'd like to start this page off with a question. How do you kill one thread from within another? Here's some code that shows the problem:

   1 import threading
   2 import time
   3 
   4 class Worker(threading.Thread):
   5   def __init__(self, eventChannel, eventHandler):
   6     self.eventChannel = eventChannel
   7     self.eventHandler = eventHandler
   8     self.stopFlag = 0
   9 
  10   def shutdown(self):
  11     self.stopFlag = 1
  12 
  13   def run(self):
  14     self.stopFlag = 0
  15     while not self.stopFlag:
  16       event = self.eventChannel.waitEvent() # blocking call
  17       self.eventHandler.dispatchEvent(event)
  18 
  19 
  20 eventChannel = EventChannel()
  21 eventHandler = EventHandler()
  22 worker = Worker(eventChannel, eventHandler)
  23 worker.run()
  24 time.sleep(20)
  25 worker.shutdown()

The problem here is that EventChannel.waitEvent() is a blocking operation. So if no event ever arrives, then our worker thread never stops. Suggestions? --ChrisSteinbach

Unable to edit the page? See the FrontPage for instructions.