sam05
sam05

Reputation: 31

python kill child thread in multithreading

I have this simple program to calculate square root of a series of numbers I want to terminate the program in case a child thread encounters exception

My code

from queue import Queue
from threading import Thread
import logging
import time
import sys

def gen_sqrt(q):
    while True:
        try :
            num = q.get()
            sqrt = num * num
            logging.debug('Sqrt of %s is %s',num,sqrt)
            q.task_done()
        except Exception as e:
            logging.debug("Can't process num %s, %s",num,str(e))
            exit_app = True

logging.debug('***Spawning Main thread');

logging.basicConfig(level=logging.DEBUG, format='[%(levelname)s](%(threadName)-10s) %(message)s',)

num_threads = 4
num_q = Queue()
exit_app = False

#for i in range(5):
for i in (1,2,3,4,'x',5):
        num_q.put(i)



for i in range(num_threads):
    if exit_app is True:
        sys.exit(1)
    else:
        #print('Exitapp :',exit_app,end='\n')
        worker = Thread(target=gen_sqrt, args=(num_q,))
        worker.daemon = True
        worker.start()

num_q.join();
logging.debug('***Done');

Problem is, my code is throwing the exception but not able to exit without keyboard interrupt.

output
[DEBUG](MainThread) ***Spawning Main thread
[DEBUG](Thread-1  ) Sqrt of 1 is 1
[DEBUG](Thread-2  ) Sqrt of 2 is 4
[DEBUG](Thread-1  ) Sqrt of 3 is 9
[DEBUG](Thread-3  ) Sqrt of 4 is 16
[DEBUG](Thread-4  ) Can't process num x, can't multiply sequence by non-int of type 'str'
[DEBUG](Thread-2  ) Sqrt of 5 is 25
^CTraceback (most recent call last):
  File "sqrt.py", line 42, in <module>
    num_q.join();
  File "/usr/local/lib/python3.3/queue.py", line 86, in join
    self.all_tasks_done.wait()
  File "/usr/local/lib/python3.3/threading.py", line 184, in wait
    waiter.acquire()
KeyboardInterrupt

I searched stackoverflow, most answers to this kind of problem are ending up with code even bigger than this program

Any quick pythonic way to do the kill

Thanks Sam

Upvotes: 0

Views: 2333

Answers (1)

J. Doe
J. Doe

Reputation: 23

Try this:

from queue import Queue
from threading import Thread
import logging
import time
import sys

main_thread = threading.current_thread()

def gen_sqrt(q):
    while True:
        if not main_thread.is_alive():
            break
        try :
            num = q.get()
            sqrt = num * num
            logging.debug('Sqrt of %s is %s',num,sqrt)
            q.task_done()
        except Exception as e:
            logging.debug("Can't process num %s, %s",num,str(e))
            exit_app = True

Upvotes: 1

Related Questions