how can a child thread notify a parent thread its status?
lists at cheimes.de
Sat Jul 25 01:53:19 CEST 2009
scriptlearner at gmail.com wrote:
> My parent thread keeps a counter for the number of free child workers
> (say 100) and initializes some child threads and call child.start().
> Once the number of free child workers reach 0, the parent thread will
> wait until some at least one child thread finishes and then it will
> initialize another child thread.
> My question is, how can a child thread notify the parent that it's
> done so that the parent can call join() on it? I am not sure how a
> child thread can send a signal to its parent while it may not even
> know anything about it's parent. Can you guys please provide some
> suggestions? Some code samples will be nice. Thanks.
You are using the wrong approach here. There is a much easier solution
to your problem although it's not obvious in the first place. In this
approach the worker threads don't have to notify the parent thread that
they are ready.
The main thread creates a queue and a bunch of worker threads that are
pulling tasks from the queue. As long as the queue is empty all worker
threads block and do nothing. When a task is put into the queue a random
worker thread acquires the task, does it job and sleeps as soon as its
ready. That way you can reuse a thread over and over again without
creating a new worker threads.
When you need to stop the threads you put a kill object into the queue
that tells the thread to shut down instead of blocking on the queue.
More information about the Python-list