如何在Python中使用執行緒程式設計


執行緒有時被稱為輕量級程序,它們不需要大量的記憶體開銷;它們比程序更便宜。執行緒有一個開始,一個執行序列和一個結束。

Python 3中有兩個模組支援執行緒的使用:

  • _thread − Python 3中已棄用

  • threading − 在Python 2.4中引入

threading模組

Python 2.4中包含的較新的threading模組比thread模組提供了更強大、更高級別的執行緒支援。

threading模組公開了thread模組的所有方法,並提供了一些附加方法:

  • threading.activeCount() − 返回正在活動的執行緒物件數量。

  • threading.currentThread() − 返回呼叫方執行緒控制中的執行緒物件數量。

  • threading.enumerate() − 返回當前正在活動的所有執行緒物件的列表。

threading模組包含實現threading的Thread類。Thread類提供的方法如下:

  • run() − run()方法是執行緒的入口點。

  • start() − start()方法透過呼叫run方法來啟動執行緒。

  • join([time]) − join()等待執行緒終止。

  • isAlive() − isAlive()方法檢查執行緒是否仍在執行。

  • getName() − getName()方法返回執行緒的名稱。

  • setName() − setName()方法設定執行緒的名稱。

編寫執行緒程式

Python提供的threading模組包含一個易於實現的鎖機制,允許您同步執行緒。透過呼叫Lock()方法建立一個新的鎖,該方法返回新的鎖。

新鎖物件的acquire(blocking)方法用於強制執行緒同步執行。可選的blocking引數允許您控制執行緒是否等待獲取鎖。如果blocking設定為0,則如果無法獲取鎖,執行緒立即返回0值;如果獲取了鎖,則返回1。如果blocking設定為1,則執行緒阻塞並等待鎖被釋放。

示例

新鎖物件的release()方法用於在不再需要鎖時釋放鎖。

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 ("Starting " + self.name) # Get lock to synchronize threads threadLock.acquire() print_time(self.name, self.counter, 3) # Free lock to release next thread 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 = [] # Create new threads thread1 = myThread(1, "Thread-1", 1) thread2 = myThread(2, "Thread-2", 2) # Start new Threads thread1.start() thread2.start() # Add threads to thread list threads.append(thread1) threads.append(thread2) # Wait for all threads to complete for t in threads: t.join() print ("Exiting Main Thread")

輸出

Starting Thread-1
Starting Thread-2
Thread-1: Mon Sep 19 08:57:59 2022
Thread-1: Mon Sep 19 08:58:00 2022
Thread-1: Mon Sep 19 08:58:01 2022
Thread-2: Mon Sep 19 08:58:03 2022
Thread-2: Mon Sep 19 08:58:05 2022
Thread-2: Mon Sep 19 08:58:07 2022
Exiting Main Thread

更新於:2022年9月19日

212 次瀏覽

啟動您的職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.