dimanche 20 septembre 2015

How to handle errors/exceptions when spawning a thread (pattern)

Sometimes I want to start a thread but I want to know whether or not it started and initialized correctly and handle an exception instead. Usually (without the thread) I can do something like this:

try:
    do_something()
except:
    some error handling

With another thread of course I can't handle exceptions like this because the spawning function returns immediately and only throws when starting the thread itself fails.

So what I would like to do is s.th. like this:

try:
    t = thread(my_fn)
    t.initialize()
    t.proceed()
except:
    some error handling

With the stuff inside t.initialize() already being run in the new thread (because for thread-safety reasons I don't want to run the initialization from a different thread than the rest)

One possible way to to do what I'm talking about could look like this:

my_fn(signal):
    try:
        do_some()
        initialization()
        signal.send('ok')
    catch Exception as e:
        signal.send(e)
    do_all()
    other_stuff()

main():
    s = signal()
    thread(my_fn, s).run()
    try:
        s.wait()
        print('thread initialized correctly!')
    except e:
        print('an error occured: ', e)
        exit(-1)
    do_stuff()
    in_main_thread()

I could live with this approach but I wonder if there's some elaboration about this (or maybe even a more elegant approach)

Aucun commentaire:

Enregistrer un commentaire