Python進階(三十四)-Python

  • 2020 年 1 月 13 日
  • 筆記

Python進階(三十四)-Python3多執行緒解讀

執行緒講解

  多執行緒類似於同時執行多個不同程式,多執行緒運行有如下優點:

  • 使用執行緒可以把佔據長時間的程式中的任務放到後台去處理。
  • 用戶介面可以更加吸引人,這樣比如用戶點擊了一個按鈕去觸發某些事件的處理,可以彈出一個進度條來顯示處理的進度。
  • 程式的運行速度可能加快。
  • 在一些等待的任務實現上如用戶輸入、文件讀寫和網路收發數據等,執行緒就比較有用了。在這種情況下我們可以釋放一些珍貴的資源如記憶體佔用等等。

  執行緒在執行過程中與進程還是有區別的。每個獨立的執行緒有一個程式運行的入口、順序執行序列和程式的出口。但是執行緒不能夠獨立執行,必須依存在應用程式中,由應用程式提供多個執行緒執行控制。   每個執行緒都有他自己的一組CPU暫存器,稱為執行緒的上下文,該上下文反映了執行緒上次運行該執行緒的CPU暫存器的狀態。 指令指針堆棧指針暫存器是執行緒上下文中兩個最重要的暫存器,執行緒總是在進程的上下文中運行的,這些地址都用於標誌擁有執行緒的進程地址空間中的記憶體。   執行緒可以被搶佔(中斷)。   在其他執行緒正在運行時,執行緒可以暫時擱置(也稱為睡眠) – 這就是執行緒的退讓。   執行緒可以分為:

  • 內核執行緒:由作業系統內核創建和撤銷。
  • 用戶執行緒:不需要內核支援而在用戶程式中實現的執行緒。

  Python3 執行緒中常用的兩個模組為:

  • _thread
  • threading(推薦使用)

  thread 模組已被廢棄。用戶可以使用 threading 模組代替。所以,在 Python3 中不能再使用」thread」 模組。為了兼容性,Python3 將 thread 重命名為 「_thread」。

開始學習Python執行緒

  Python中使用執行緒有兩種方式:函數或者用類來包裝執行緒對象。   函數式:調用 _thread 模組中的start_new_thread()函數來產生新執行緒。語法如下:

_thread.start_new_thread ( function, args[, kwargs] )

  參數說明:

  • function – 執行緒函數。
  • args – 傳遞給執行緒函數的參數,他必須是個tuple類型。
  • kwargs – 可選參數。

  實例:

#!/usr/bin/python3    import _thread  import time    # 為執行緒定義一個函數  def print_time( threadName, delay):      count = 0      while count < 5:          time.sleep(delay)          count += 1          print ("%s: %s" % ( threadName, time.ctime(time.time()) ))    # 創建兩個執行緒  try:      _thread.start_new_thread( print_time, ("Thread-1", 2, ) )      _thread.start_new_thread( print_time, ("Thread-2", 4, ) )  except:      print ("Error: 無法啟動執行緒")    while 1:      pass

  執行以上程式輸出結果如下:

執行緒模組

  Python3 通過兩個標準庫 _thread 和 threading 提供對執行緒的支援。

  • _thread 提供了低級別的、原始的執行緒以及一個簡單的鎖,它相比於 threading 模組的功能還是比較有限的。
  • threading 模組除了包含 _thread 模組中的所有方法外,還提供的其他方法:
  • threading.currentThread(): 返回當前的執行緒變數。
  • threading.enumerate(): 返回一個包含正在運行的執行緒的list。正在運行指執行緒啟動後、結束前,不包括啟動前和終止後的執行緒。
  • threading.activeCount(): 返回正在運行的執行緒數量,與len(threading.enumerate())有相同的結果。

  除了使用方法外,執行緒模組同樣提供了Thread類來處理執行緒,Thread類提供了以下方法:

  • run(): 用以表示執行緒活動的方法。
  • start():啟動執行緒活動。
  • join([time]): 等待至執行緒中止。這阻塞調用執行緒直至執行緒的join() 方法被調用中止-正常退出或者拋出未處理的異常-或者是可選的超時發生。
  • isAlive(): 返回執行緒是否活動的。
  • getName(): 返回執行緒名。
  • setName(): 設置執行緒名。

使用 threading 模組創建執行緒

  我們可以通過直接從 threading.Thread 繼承創建一個新的子類,並實例化後調用 start() 方法啟動新執行緒,即它調用了執行緒的 run() 方法:

#!/usr/bin/python3    import threading  import time    exitFlag = 0    class myThread (threading.Thread):      def __init__(self, threadID, name, counter):          threading.Thread.__init__(self)          self.threadID = threadID          self.name = name          self.counter = counter      def run(self):          print ("開始執行緒:" + self.name)          print_time(self.name, self.counter, 5)          print ("退出執行緒:" + self.name)    def print_time(threadName, delay, counter):      while counter:          if exitFlag:              threadName.exit()          time.sleep(delay)          print ("%s: %s" % (threadName, time.ctime(time.time())))          counter -= 1    # 創建新執行緒  thread1 = myThread(1, "Thread-1", 1)  thread2 = myThread(2, "Thread-2", 2)    # 開啟新執行緒  thread1.start()  thread2.start()  thread1.join()  thread2.join()  print ("退出主執行緒")

  以上程式執行結果如下:

執行緒同步

  如果多個執行緒共同對某個數據修改,則可能出現不可預料的結果,為了保證數據的正確性,需要對多個執行緒進行同步。   使用 Thread 對象的 Lock 和 Rlock 可以實現簡單的執行緒同步,這兩個對象都有 acquire 方法和 release 方法,對於那些需要每次只允許一個執行緒操作的數據,可以將其操作放到 acquire 和 release 方法之間。如下:   多執行緒的優勢在於可以同時運行多個任務(至少感覺起來是這樣)。但是當執行緒需要共享數據時,可能存在數據不同步的問題。   考慮這樣一種情況:一個列表裡所有元素都是0,執行緒」set」從後向前把所有元素改成1,而執行緒」print」負責從前往後讀取列表並列印。   那麼,可能執行緒」set」開始改的時候,執行緒」print」便來列印列表了,輸出就成了一半0一半1,這就是數據的不同步。為了避免這種情況,引入了鎖的概念。   鎖有兩種狀態——鎖定和未鎖定。每當一個執行緒比如」set」要訪問共享數據時,必須先獲得鎖定;如果已經有別的執行緒比如」print」獲得鎖定了,那麼就讓執行緒」set」暫停,也就是同步阻塞;等到執行緒」print」訪問完畢,釋放鎖以後,再讓執行緒」set」繼續。   經過這樣的處理,列印列表時要麼全部輸出0,要麼全部輸出1,不會再出現一半0一半1的尷尬場面。   實例:

#!/usr/bin/python3    import threading  import time    class myThread (threading.Thread):      def __init__(self, threadID, name, counter):          threading.Thread.__init__(self)          self.threadID = threadID          self.name = name          self.counter = counter      def run(self):          print ("開啟執行緒: " + self.name)          # 獲取鎖,用於執行緒同步          threadLock.acquire()          print_time(self.name, self.counter, 3)          # 釋放鎖,開啟下一個執行緒          threadLock.release()    def print_time(threadName, delay, counter):      while counter:          time.sleep(delay)          print ("%s: %s" % (threadName, time.ctime(time.time())))          counter -= 1    threadLock = threading.Lock()  threads = []    # 創建新執行緒  thread1 = myThread(1, "Thread-1", 1)  thread2 = myThread(2, "Thread-2", 2)    # 開啟新執行緒  thread1.start()  thread2.start()    # 添加執行緒到執行緒列表  threads.append(thread1)  threads.append(thread2)    # 等待所有執行緒完成  for t in threads:      t.join()  print ("退出主執行緒")

  執行以上程式,輸出結果為:

執行緒優先順序隊列(Queue)

  Python 的 Queue 模組中提供了同步的、執行緒安全的隊列類,包括FIFO(先入先出)隊列Queue,LIFO(後入先出)隊列LifoQueue,和優先順序隊列 PriorityQueue。   這些隊列都實現了鎖原語,能夠在多執行緒中直接使用,可以使用隊列來實現執行緒間的同步。   Queue 模組中的常用方法:

  • Queue.qsize() 返回隊列的大小
  • Queue.empty() 如果隊列為空,返回True,反之False
  • Queue.full() 如果隊列滿了,返回True,反之False
  • Queue.full 與 maxsize 大小對應
  • Queue.get([block[, timeout]])獲取隊列,timeout等待時間
  • Queue.get_nowait() 相當Queue.get(False)
  • Queue.put(item) 寫入隊列,timeout等待時間
  • Queue.put_nowait(item) 相當Queue.put(item, False)
  • Queue.task_done() 在完成一項工作之後,Queue.task_done()函數向任務已經完成的隊列發送一個訊號
  • Queue.join() 實際上意味著等到隊列為空,再執行別的操作

  實例:

#!/usr/bin/python3    import queue  import threading  import time    exitFlag = 0    class myThread (threading.Thread):      def __init__(self, threadID, name, q):          threading.Thread.__init__(self)          self.threadID = threadID          self.name = name          self.q = q      def run(self):          print ("開啟執行緒:" + self.name)          process_data(self.name, self.q)          print ("退出執行緒:" + self.name)    def process_data(threadName, q):      while not exitFlag:          queueLock.acquire()          if not workQueue.empty():              data = q.get()              queueLock.release()              print ("%s processing %s" % (threadName, data))          else:              queueLock.release()          time.sleep(1)    threadList = ["Thread-1", "Thread-2", "Thread-3"]  nameList = ["One", "Two", "Three", "Four", "Five"]  queueLock = threading.Lock()  workQueue = queue.Queue(10)  threads = []  threadID = 1    # 創建新執行緒  for tName in threadList:      thread = myThread(threadID, tName, workQueue)      thread.start()      threads.append(thread)      threadID += 1    # 填充隊列  queueLock.acquire()  for word in nameList:      workQueue.put(word)  queueLock.release()    # 等待隊列清空  while not workQueue.empty():      pass    # 通知執行緒是時候退出  exitFlag = 1    # 等待所有執行緒完成  for t in threads:      t.join()  print ("退出主執行緒")

  以上程式執行結果:

延伸閱讀

  有關執行緒與進程的區別、執行緒鎖的具體內容詳見博文《劍指Offer——知識點儲備-Java基礎》、《Java進階(四十三)執行緒與進程的區別》、《Java進階(四十四)執行緒與進程的特徵及區別》。