python 强行杀死子线程例子

import threading
import time
import inspect
import ctypes


def stop_thread(thread, exctype=SystemExit):
    """raises the exception, performs cleanup if needed"""
    tid = ctypes.c_long(thread.ident)
    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")

def print_time(s):
    while True:
        print(str(s)+'-------111111111111')
        a=0
        while True:
            a+=1
            print(str(s) + "-------" + str(a))
            if a==10:
                break
            time.sleep(0.5)
        time.sleep(1)

t_list=[]
if __name__ == "__main__":
    while True:
        a=input('输入一个数')
        t = threading.Thread(target=print_time,args=(str(int(time.time()))[-3:],))
        if a=='1':
            t.start()
            t_list.append(t)
        if a=='2':
            print(t_list)
            for i in t_list:
                stop_thread(i)
                print("stoped")
            t_list=[]
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容