About object reference and threads

Peter Hansen peter at engcorp.com
Mon Jan 27 13:21:15 EST 2003


Grumfish wrote:
> 
> How do I tell a Thread object what Queue object to use? I have a
> parent object that has a Queue and a Thread as members. I want the
> parent object to create the thread, tell it to write to to the Queue
> object, then start the Thread. How do I do this? How do I get a
> reference to an object?

Untested code snippets:

class Task(threading.Thread):
    def __init__(self, queue):
        threading.Thread.__init__(self)
        self.queue = queue

    def run(self):
        # do stuff like write to self.queue
        ...


In the parent code:

import Queue
q = Queue.Queue()
task = Task(q)
task.start()
# do stuff like read from "q"
...

In other words, pass the Queue object you want to use in to the
Thread when you create it.  There are some alternatives, but this
one generally works best.

-Peter




More information about the Python-list mailing list