Python threading question (Working with a method that blocks forever)

Posted by Nix on Stack Overflow See other posts from Stack Overflow or by Nix
Published on 2011-02-14T21:14:37Z Indexed on 2011/02/14 23:25 UTC
Read the original article Hit count: 137

I am trying to wrap a thread around some receiving logic in python. Basically we have an app, that will have a thread in the background polling for messages, the problem I ran into is that piece that actually pulls the messages waits forever for a message. Making it impossible to terminate... I ended up wrapping the pull in another thread, but I wanted to make sure there wasn't a better way to do it.

Original code:

class Manager:
   def __init__(self):
        receiver = MessageReceiver()
        receiver.start()
        #do other stuff...

class MessageReceiver(Thread):
   receiver = Receiver()

   def __init__(self):
        Thread.__init__(self)


   def run(self):           
       #stop is a flag that i use to stop the thread...
       while(not stopped ):
          #can never stop because pull below blocks
          message  = receiver.pull()
          print "Message" + message   

What I refectored to:

class Manager:
   def __init__(self):
        receiver = MessageReceiver()
        receiver.start()

class MessageReceiver(Thread):

   receiver = Receiver()
   def __init__(self):
        Thread.__init__(self)
   def run(self):
       pullThread = PullThread(self.receiver)
       pullThread.start()

       #stop is a flag that i use to stop the thread...
       while(not stopped and pullThread.last_message ==None): pass

       message  =  pullThread.last_message
       print "Message" + message

class PullThread(Thread):
   last_message = None
   def __init__(self, receiver):
        Thread.__init(self, target=get_message, args=(receiver))

   def get_message(self, receiver):
        self.last_message = None
        self.last_message = receiver.pull()
        return self.last_message

I know the obvious locking issues exist, but is this the appropriate way to control a receive thread that waits forever for a message?

One thing I did notice was this thing eats 100% cpu while waiting for a message... **If you need to see the stopping logic please let me know and I will post.

© Stack Overflow or respective owner

Related posts about python

Related posts about multithreading