Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux 程式設計 >> Linux 程式設計

Python 多執行緒編程入門:GIL、進程與 Queue 工作模型

Python 在併發這件事上並不匱乏選擇:標準庫就提供了執行緒、進程與非同步 I/O 的支援,並用高階模組把這些底層機制包成好上手的介面;標準庫之外,還有 Twisted、Stackless、processing 等第三方方案。

但要先記住一個前提:受 GIL(全域直譯器鎖) 限制,CPU 密集型任務無法真正從多執行緒受益。這類運算吃重的程式,該用多進程,或採用「進程為主、執行緒為輔」的混合模型;反之,I/O 密集型任務(爬蟲、大量網路請求)用執行緒的效果就很好。

進程與執行緒的分野

兩者最根本的差異在於是否共享狀態、記憶體與資源。執行緒輕量、彼此溝通容易,這既是它的優勢,也是它的麻煩來源——死鎖、競爭條件(race condition)與調試複雜度都由此而生。所幸在 Python 中,GIL 加上 queue 模組把同步細節收攏起來,寫執行緒的門檻比其他語言低得多。

一個可直接運行的範例

#!/usr/bin/env python
import Queue
import threading
import urllib2
import time

hosts = ["https://www.baidu.com", "https://www.sina.com.cn", "https://www.letv.com"]

class ThreadUrl(threading.Thread):
    def __init__(self, queue):
        threading.Thread.__init__(self)
        self.queue = queue

    def run(self):
        while True:
            host = self.queue.get()
            url = urllib2.urlopen(host)
            print url.read(1024)
            self.queue.task_done()

def main():
    queue = Queue.Queue()
    for i in range(5):
        t = ThreadUrl(queue)
        t.setDaemon(True)
        t.start()

    for host in hosts:
        queue.put(host)

    queue.join()

if __name__ == "__main__":
    start = time.time()
    main()
    print "Elapsed Time:%s" % (time.time() - start)

這個模型的運作步驟

  1. 建立 Queue.Queue() 實例,把待處理的資料放進去。
  2. 把佇列傳給自訂的執行緒類別,該類別繼承 threading.Thread。
  3. 建立守護執行緒池(setDaemon(True))。
  4. 每個執行緒在 run() 中從佇列 pop 一筆資料,做完工作後呼叫 task_done() 送出完成訊號。
  5. 主程式對佇列呼叫 join(),等佇列清空後才退出。

把執行緒設為守護(daemon)的意義是:主執行緒不必逐一等待,只要守護執行緒還在活動,程式就會持續運行;一旦主流程決定結束,背景執行緒會被一併收掉。這讓流程控制變得單純——你要嘛 join() 等全部做完,要嘛直接走人。

補充說明 join() 的語意:它會保持阻塞,直到佇列中所有項目都被處理完。每 put 一筆,未完成任务數加一;每呼叫一次 task_done() 就減一;歸零時 join() 才解除阻塞。

版本提醒

以上範例為 Python 2 寫法。若你在 Python 3,請把 Queue 改為 queue、urllib2 改為 urllib.request,並把 print 改為函數形式;若想避開 GIL 又不想處理進程間傳遞,也可以評估 concurrent.futures 的 ThreadPoolExecutor 與 ProcessPoolExecutor。

Copyright © Linux教程網 All Rights Reserved