Differences between revisions 8 and 9
Revision 8 as of 2002-09-03 06:42:10
Size: 1274
Editor: cacher3-ext
Comment:
Revision 9 as of 2002-10-10 22:10:12
Size: 1719
Editor: guardnet
Comment:
Deletions are marked like this. Additions are marked like this.
Line 47: Line 47:
= Call to C function blocks all threads =

I have a C module that does database queries. Those queries go off to an SQL server
to be processed. I would like to use my query function within threads and to have it work
like {{{time.sleep()}}}, that is, block the current thread until it finishes but allow other threads to continue operation. I haven't seen this issue addressed in any of the books I have.
 
* ''Any suggestions, anyone?''

Stopping Threads

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 start(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.start()
  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. (EventChannel and EventHandler are classes I've invented for this example)

Suggestions

  • Make the shutdown() method put some harmless event on the event channel:

  def shutdown(self):
    self.stopFlag = 1
    self.eventChannel.push_event(NullEvent())
  • any other ideas?

Call to C function blocks all threads

I have a C module that does database queries. Those queries go off to an SQL server to be processed. I would like to use my query function within threads and to have it work like time.sleep(), that is, block the current thread until it finishes but allow other threads to continue operation. I haven't seen this issue addressed in any of the books I have.

* Any suggestions, anyone?

ThreadProgramming (last edited 2008-11-15 13:59:41 by localhost)

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