1. 程式人生 > 程式設計 >python中threading開啟關閉執行緒操作

python中threading開啟關閉執行緒操作

在python中啟動和關閉執行緒:

首先匯入threading

import threading

然後定義一個方法

def serial_read():
...
...

然後定義執行緒,target指向要執行的方法

myThread = threading.Thread(target=serial_read)

啟動它

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)

補充知識:python threading實現Thread的修改值,開始,執行,停止,並獲得內部值

下面的半模版程式碼在 win7+python3.63 執行通過並且實測可行,為了廣大想要實現python的多執行緒停止的同學

import threading
import time
class MyThread(threading.Thread):
  def __init__(self):
    threading.Thread.__init__(self)
    self.Flag=True        #停止標誌位
    self.Parm=0         #用來被外部訪問的
    #自行新增引數
  
  def run(self):
    while(True):
      if(not self.Flag):
        break
      else:
        time.sleep(2)
  
  def setFlag(self,parm):     #外部停止執行緒的操作函式
    self.Flag=parm #boolean
 
  def setParm(self,parm):     #外部修改內部資訊函式
    self.Parm=parm
 
  def getParm(self):       #外部獲得內部資訊函式
    return self.Parm
 
 
if __name__=="__main__":
  testThread=MyThread()
  testThread.setDaemon(True)     #設為保護執行緒,主程序結束會關閉執行緒
  testThread.getParm()      #獲得執行緒內部值
  testThread.setParm(1)      #修改執行緒內部值
  testThread.start()       #開始執行緒
  print(testThread.getParm())    #輸出內部資訊
  time.sleep(2)          #主程序休眠 2 秒
  testThread.setFlag(False)      #修改執行緒執行狀態
  time.sleep(2)          #2019.04.25 修改
  print(testThread.is_alive())  #檢視執行緒執行狀態

於2018-08-24修正一次,修正為在繼承thread.Thread時,沒有對父類初始化

舊:

def __init__(self):
    self.Flag=True        #停止標誌位
    self.Parm=0         #用來被外部訪問的
    #自行新增引數

新:

def __init__(self):
    threading.Thread.__init__(self)
    self.Flag=True        #停止標誌位
    self.Parm=0         #用來被外部訪問的
    #自行新增引數

於2019年4月25日進行第二次修正,發現設定flag值後仍為true輸出的情況,原因是輸出在修改完成前執行,睡眠後結果正常

以上這篇python中threading開啟關閉執行緒操作就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支援我們。