凌的博客

您现在的位置是: 首页 > 学无止境 > python > 

python

python 主线程强制关闭子线程

2019-08-25 python 1759
import threading, ctypes, inspect
import time
import os


class WorkThread(threading.Thread):
    def run(self):
        try:
            while True:
                time.sleep(3)
                print("run.. thread")
        except Exception as e:
            print(str(e))

    def stop(self):
        self._async_raise(self.ident, SystemExit)

    def _async_raise(self, tid, exctype):
        """raises the exception, performs cleanup if needed"""
        tid = ctypes.c_long(tid)
        if not inspect.isclass(exctype):
            exctype = type(exctype)
        res = ctypes.pythonapi.PyThreadState_SetAsyncExc(tid, ctypes.py_object(exctype))
        if res == 0:
            raise ValueError("invalid thread id")
        elif res != 1:
            # """if it returns a number greater than one, you're in trouble,
            # and you should call it again with exc=NULL to revert the effect"""
            ctypes.pythonapi.PyThreadState_SetAsyncExc(tid, None)
            raise SystemError("PyThreadState_SetAsyncExc failed")


print('Press Ctrl+{0} to exit'.format('Break' if os.name == 'nt' else 'C'))
try:
    t = WorkThread()
    t.start()
    i = 0

    while True:
        time.sleep(1)
        print("main thread")
        i = i+1
        if i>3:
            t.stop() #强制关闭子线程

except Exception as e:
    print(str(e))


文章评论

0条评论