Python多線程基本操作


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

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

Python中使用線程有兩種方式函數或者用類來包裝線程對象

函數式:調用thread模塊中的start_new_thread()函數來產生新線程。語法如下:

 

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

參數說明:

  • function - 線程函數。
  • args - 傳遞給線程函數的參數,他必須是個tuple類型。
  • kwargs - 可選參數。

使用Thread模塊創建線程

import _thread import time # 定義一個函數
def print_time(threadName , delay): count = 0 while count < 5: time.sleep(delay) count += 1
        print(threadName,count) #創建兩個線程
try: _thread.start_new_thread(print_time,("Thread-1",2)) _thread.start_new_thread(print_time,("Thread-2",4)) except: print("Error : unable to start thread") while 1: pass

結果:

Thread-1 1 Thread-1 2 Thread-2 1 Thread-1 3 Thread-1 4 Thread-2 2 Thread-1 5 Thread-2 3 Thread-2 4 Thread-2 5

使用Threading模塊創建線程

import threading import time exitFlag = 0 class myThread(threading.Thread):  # 繼承父類threading.Thread
    def __init__(self, threadID, name, counter): threading.Thread.__init__(self) self.threadID = threadID self.name = name self.counter = counter def run(self):  # 把要執行的代碼寫到run函數里面 線程在創建后會直接運行run函數
        print("Starting " + self.name) print_time(self.name, self.counter, 5) print("Exiting " + self.name) def print_time(threadName, delay, counter): while counter: if exitFlag: (threading.Thread).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() print("Exiting Main Thread")

結果:

Starting Thread-1 Starting Thread-2 Exiting Main Thread Thread-1: Thu Mar 21 09:10:03 2013 Thread-1: Thu Mar 21 09:10:04 2013 Thread-2: Thu Mar 21 09:10:04 2013 Thread-1: Thu Mar 21 09:10:05 2013 Thread-1: Thu Mar 21 09:10:06 2013 Thread-2: Thu Mar 21 09:10:06 2013 Thread-1: Thu Mar 21 09:10:07 2013 Exiting Thread-1 Thread-2: Thu Mar 21 09:10:08 2013 Thread-2: Thu Mar 21 09:10:10 2013 Thread-2: Thu Mar 21 09:10:12 2013 Exiting Thread-2

線程同步

如果多個線程共同對某個數據修改,則可能出現不可預料的結果,為了保證數據的正確性,需要對多個線程進行同步。

使用Thread對象的LockRlock可以實現簡單的線程同步,這兩個對象都有acquire方法和release方法,對於那些需要每次只允許一個線程操作的數據,可以將其操作放到acquire和release方法之間。如下:

多線程的優勢在於可以同時運行多個任務(至少感覺起來是這樣)。但是當線程需要共享數據時,可能存在數據不同步的問題。

考慮這樣一種情況:一個列表里所有元素都是0,線程"set"從后向前把所有元素改成1,而線程"print"負責從前往后讀取列表並打印。

那么,可能線程"set"開始改的時候,線程"print"便來打印列表了,輸出就成了一半0一半1,這就是數據的不同步。為了避免這種情況,引入了鎖的概念。

鎖有兩種狀態——鎖定和未鎖定。每當一個線程比如"set"要訪問共享數據時,必須先獲得鎖定;如果已經有別的線程比如"print"獲得鎖定了,那么就讓線程"set"暫停,也就是同步阻塞;等到線程"print"訪問完畢,釋放鎖以后,再讓線程"set"繼續

經過這樣的處理,打印列表時要么全部輸出0,要么全部輸出1,不會再出現一半0一半1的尷尬場面。

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) # 獲得鎖,成功獲得鎖定后返回True
        # 可選的timeout參數不填時將一直阻塞直到獲得鎖定
        # 否則超時后將返回False
 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("Exiting Main Thread")

結果:

Starting Thread-1 Starting Thread-2 Thread-1: Tue Apr 24 11:09:33 2018 Thread-1: Tue Apr 24 11:09:34 2018 Thread-1: Tue Apr 24 11:09:35 2018 Thread-2: Tue Apr 24 11:09:37 2018 Thread-2: Tue Apr 24 11:09:39 2018 Thread-2: Tue Apr 24 11:09:41 2018 Exiting Main Thread

線程優先級隊列( 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() 實際上意味着等到隊列為空,再執行別的操作
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("Starting " + self.name) process_data(self.name, self.q) print("Exiting " + 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("Exiting Main Thread")

結果:

Starting Thread-1 Starting Thread-2 Starting Thread-3 Thread-2 processing One Thread-1 processing Two Thread-3 processing Three Thread-3 processing Four Thread-1 processing Five Exiting Thread-2 Exiting Thread-3 Exiting Thread-1 Exiting Main Thread

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM