0

Related: Catch a thread's exception in the caller thread in Python

When I catch exception in a child thread:
I need to let the thread caller to know

In the related posting, accepted answer checks for queue which is fine but it prevents the main caller from doing anything else because its keep checking the queue

So it would be ideal if it's event based.

The solution should be: main caller does things (not continuously checking the queue for error in child thread) and if something goes bad inside child thread, child thread lets main caller know through some event and main caller process the error.

I ve been looking at different articles and solutions but all event stuff is directed towards main caller communicating to a child thread and not vice versa

any solution that a child thread communicating to the caller via events?

Community
  • 1
  • 1
ealeon
  • 12,074
  • 24
  • 92
  • 173

1 Answers1

0

There is no such thing as a "thread caller". All threads are equal.

In your head the "main thread" is something special because Python gives that to you for free but as far as Python is concerned, the main thread is just a tread like any other.

So your question boils down to: How can I exchange information between two threads?

With one or more queues.

Usually, the pseudo code looks like this:

  1. Create N workers, connected to an input and an output queue.
  2. Put work into the input queue
  3. Wait for results on the output queue
  4. Join the threads

Note that you don't have to block in step #3. You can also ask the queue whether it has any elements. If so, then get() won't block. If it's empty, then you can do other things.

Step #4 is often more simple to implement, when you define a "kill" command to which the threads respond with a "I'm done" reply.

You can then send N kill commands and wait for the N replies. Afterwards, you can be sure that all threads are done.

Aaron Digulla
  • 321,842
  • 108
  • 597
  • 820
  • whoever that calls threading.Thread() is what im saying by the caller – ealeon May 11 '15 at 15:49
  • i know the get could be a non-blocking but.. then you have to ask the question do i have to check the queue the whole time the program is running? that sounds like a bad solution – ealeon May 11 '15 at 15:50
  • And how often do you check and when do you check and all that. If its event based then yoi dont have to answer those questions – ealeon May 11 '15 at 16:01