Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
272 views
in Technique[技术] by (71.8m points)

multithreading - Python uncaught exceptions in main not killing threads


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

This seems to be hackish, but still something to start with.

prog1.py - I have added sleep of 5 seconds so you can see the thread running and then gets completed.

import modx1
import time


mod_obj = modx1.Moddy()
time.sleep(5)
raise Exception('DIE UNEXPECTEDLY')

try:
    raise Exception('known problem here')
except Exception:
    mod_obj.kill_event.set()

modx1.py -> Check for the boolean you set and also the status of main thread.

import ctypes
import threading
import subprocess
from time import sleep


class Moddy():
    def __init__(self):
        self.kill_event = threading.Event()
        self.my_thread = threading.Thread(target=self.thread_func)
        self.my_thread.start()

    def thread_func(self):
        while not self.kill_event.is_set() and threading.main_thread().is_alive():
            print('thread still going....')
            sleep(2)

OUTPUT

thread still going....
thread still going....
thread still going....
Traceback (most recent call last):
  File "/Users/gaurishankarbadola/PycharmProjects/untitled1/prog1.py", line 8, in <module>
    raise Exception('DIE UNEXPECTEDLY')
Exception: DIE UNEXPECTEDLY

Process finished with exit code 1

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...