新聞中心
在python中啟動(dòng)和關(guān)閉線程:

“專業(yè)、務(wù)實(shí)、高效、創(chuàng)新、把客戶的事當(dāng)成自己的事”是我們每一個(gè)人一直以來(lái)堅(jiān)持追求的企業(yè)文化。 創(chuàng)新互聯(lián)是您可以信賴的網(wǎng)站建設(shè)服務(wù)商、專業(yè)的互聯(lián)網(wǎng)服務(wù)提供商! 專注于成都網(wǎng)站設(shè)計(jì)、成都做網(wǎng)站、外貿(mào)網(wǎng)站建設(shè)、軟件開發(fā)、設(shè)計(jì)服務(wù)業(yè)務(wù)。我們始終堅(jiān)持以客戶需求為導(dǎo)向,結(jié)合用戶體驗(yàn)與視覺傳達(dá),提供有針對(duì)性的項(xiàng)目解決方案,提供專業(yè)性的建議,創(chuàng)新互聯(lián)建站將不斷地超越自我,追逐市場(chǎng),引領(lǐng)市場(chǎng)!
一、啟動(dòng)線程
首先導(dǎo)入threading
import threading
然后定義一個(gè)方法
def serial_read(): ... ...
然后定義線程,target指向要執(zhí)行的方法
myThread = threading.Thread(target=serial_read)
啟動(dòng)它
myThread.start()
二、停止線程
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)停止線程
stop_thread(myThread)
stop方法可以強(qiáng)行終止正在運(yùn)行或掛起的線程。
推薦學(xué)習(xí)《Python教程》
新聞標(biāo)題:創(chuàng)新互聯(lián)Python教程:python怎樣終止線程
瀏覽路徑:http://m.fisionsoft.com.cn/article/dhsejjp.html


咨詢
建站咨詢
