class T:
def start_back_thread(self,func,*args):
th = threading.Thread(target=func,args=args)
th.start()
return th.ident
def task():
while True:
print("hello")
time.sleep(1)
def task2():
while True:
print("world")
time.sleep(2)
def _async_raise(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")
def stop_thread(id):
_async_raise(id, SystemExit)
if __name__ == '__main__':
t = T()
id1 = t.start_back_thread(task)
id2 = t.start_back_thread(task2)
stop_thread(id1)
print("我是主线程")
Python创建线程,停止线程(CAPI)
最新推荐文章于 2023-04-17 21:56:53 发布