杀线程代码

import websocket
import threading
import inspect
import ctypes
import time
from websocket import ABNF

symbol = 'btc'

thread = {'id': 0, 'on': 0}


def stop(tid):
    tid = ctypes.c_long(tid)
    if not inspect.isclass(SystemExit):
        exctype = type(SystemExit)
    res = ctypes.pythonapi.PyThreadState_SetAsyncExc(tid, ctypes.py_object(SystemExit))
    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 test():
    i = 0
    while i<= 100:
        time.sleep(0.5)
        i+=1
        print('\nthe value of i from thread is:',i)
        if i == 20:
            thread['on'] = 0
            stop(thread['id'])
    


def on_message(ws, message):

    if thread['id'] == 0:
        thread['on'] = 1
        t = threading.Thread(target=test)
        t.start()
        thread['id'] = t.ident

    if thread['on'] == 0:

        print('\nt------------------------- the on is ----------------------', thread['on'])


版权声明:本文为quantifyz原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。