python threading 结束线程
生活随笔
收集整理的這篇文章主要介紹了
python threading 结束线程
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
python threading 啟動的線程,并沒有提供終止線程的方法,現總結一下在網上找到的方法
1、通過threading.Thread._Thread__stop()結束線程
import time import threading def f():while 1:time.sleep(0.1)print(1)t = threading.Thread(target=f) t.start() time.sleep(0.5) print("Stopping the thread") threading.Thread._Thread__stop(t) print("Stopped the thread")# 運行結果python2 1 1 1 1 Stopping the thread Stopped the thread# 運行結果 python31 1 1 1 Traceback (most recent call last):File "C:/work/1/reco/12月/tmp.py", line 64, in <module>threading.Thread._Thread__stop(t) AttributeError: type object 'Thread' has no attribute '_Thread__stop' Stopping the threadWindows實驗結果:python2時,p.isAlive()會報False,但實際進程并未結束。用python3會報錯。
2、使用ctypes強行殺掉線程
import threading import time import inspect import ctypesdef _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(thread):_async_raise(thread.ident, SystemExit)def print_time(e):while 2:print(e)if __name__ == "__main__":t = threading.Thread(target=print_time,args=("2"))t.start()time.sleep(0.001)stop_thread(t)print("stoped")time.sleep(2)t1 = threading.Thread(target=print_time,args=("1"))t1.start()time.sleep(0.001)stop_thread(t1)print("stoped")while 1:passwindows實測:python2 可以結束進程,python3未測。
總結
以上是生活随笔為你收集整理的python threading 结束线程的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 最全常用正则表达式大全
- 下一篇: python变量命名可以有特殊符号吗,和