新聞中心
這里有您想知道的互聯(lián)網(wǎng)營(yíng)銷解決方案
創(chuàng)新互聯(lián)Python教程:python怎么關(guān)閉線程
python關(guān)閉線程的方法:

1、利用setDaemon(True)這個(gè)函數(shù)的特性關(guān)閉線程
特性如下:主線程A中,創(chuàng)建了子線程B,并且在主線程A中調(diào)用了B.setDaemon(),這個(gè)的意思是,把主線程A設(shè)置為守護(hù)線程,這時(shí)候,要是主線程A執(zhí)行結(jié)束了,就不管子線程B是否完成,一并和主線程A退出。
2、使用ctypes強(qiáng)行殺掉線程
import threading
import time
import inspect
import ctypes
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(thread):
_async_raise(thread.ident, SystemExit)
def print_time():
while 2:
print(111111111111)
print(222222222222)
print(333333333333)
print(444444444444)
print(555555555555)
print(666666666666)
if __name__ == "__main__":
t = threading.Thread(target=print_time)
t.start()
stop_thread(t)
print("stoped")
while 1:
pass 新聞名稱:創(chuàng)新互聯(lián)Python教程:python怎么關(guān)閉線程
分享鏈接:http://m.fisionsoft.com.cn/article/dpdegpi.html


咨詢
建站咨詢
