在很多场景中,可能会涉及到结束其他线程的场景。比如,执行一个秒杀任务,启动了5个线程,当其中某个线程已经抢到或者商品已经返回没有的情况下,需要结束所有的线程.代码如下:
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:
print('error')
elif res != 1:
ctypes.pythonapi.PyThreadState_SetAsyncExc(tid, None)
raise SystemError("PyThreadState_SetAsyncExc failed")
def stop_thread(thread):
_async_raise(thread.ident, SystemExit)
直接调用stop_thread的方法,eg如下:
在创建线程的时候,用一个数组将所有的线程都存储下来,然后传入线程执行方法
threads = []
for i in range(int(args5)):
mythread = threading.Thread(target=kill,args=(i,threads))
threads.append(mythread)
for thread in threads:
thread.start()
具体线程执行方法:
def kill(i,threads):
###具体业务逻辑
time.sleep(i)
for thread in threads:
stop_thread(thread)