Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - Have parent thread handle child threads Exception

Tags:

People also ask

Can parent thread create child threads?

Thread CreationThe creating thread is the parent thread, and the created thread is a child thread. Note that any thread, including the main program which is run as a thread when it starts, can create child threads at any time.

How does Python handle exceptions in multithreading?

For catching and handling a thread's exception in the caller thread we use a variable that stores the raised exception (if any) in the called thread, and when the called thread is joined, the join function checks whether the value of exc is None, if it is then no exception is generated, otherwise, the generated ...

Do threads have parent/child relationship?

Practically yes. Pretty much every pthreads implementation out there supports it. Provided the "parent" thread doesn't complete before the newly created thread which might still be using the stack address(es) from the parent, this is fine.

Can Python run threads in parallel?

In fact, a Python process cannot run threads in parallel but it can run them concurrently through context switching during I/O bound operations. This limitation is actually enforced by GIL. The Python Global Interpreter Lock (GIL) prevents threads within the same process to be executed at the same time.


Is there a way to have the parent that spawned a new thread catch the spawned threads exception? Below is a real basic example of what I am trying to accomplish. It should stop counting when Exception is raised, but I don't know how to catch it. Are exceptions thread safe? I would love to be able to use the Subprocess module, but I am stuck using Python 2.3 and am not sure how else to do this. Possibly using the threading module?

import time
import thread

def test(): 
    try:
        test = thread.start_new_thread(watchdog, (5,))
        count(10)
    except:
        print('Stopped Counting')

def count(num):
    for i in range(num):
        print i
        time.sleep(1)

def watchdog(timeout):
    time.sleep(timeout)
    raise Exception('Ran out of time')

if __name__ == '__main__':
    test()

UPDATE

My original code was a little misleading. It am really looking for something more like this:

import time
import thread
import os

def test(): 
    try:
        test = thread.start_new_thread(watchdog, (5,))
        os.system('count_to_10.exe')
    except:
        print('Stopped Counting')

def watchdog(timeout):
    time.sleep(timeout)
    raise Exception('Ran out of time')

if __name__ == '__main__':
    test()

I am trying to create a watchdog to kill the os.system call if the program hangs up for some reason.