日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

python threading 结束线程

發布時間:2023/12/20 python 29 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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 thread

Windows實驗結果: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:pass

windows實測:python2 可以結束進程,python3未測。

總結

以上是生活随笔為你收集整理的python threading 结束线程的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。