import threading
import inspect
import ctypes
import time
def task1():
while True:
print("hello")
time.sleep(1)
def task2():
while True:
print("world")
time.sleep(2)
def _async_raise(tid, exctype):
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:
ctypes.pythonapi.PyThreadState_SetAsyncExc(tid, None)
raise SystemError("PyThreadState_SetAsyncExc failed")
def stop_thread(id):
_async_raise(id, SystemExit)
if __name__ == '__main__':
job1 = threading.Thread(task1)
job2 = threading.Thread(task2)
job1.start()
job2.start()
time.sleep(2)
stop_thread(job1.ident)
time.sleep(2)
stop_thread(job2.ident)
标签:__,raise,python,exctype,线程,关闭,time,tid,sleep From: https://www.cnblogs.com/weilaiqinkong/p/17248355.html