Python: 關於thread模塊和threading模塊的選擇

最近在閱讀Python核心編程(第二版)。
做者在多線程編程一章講到thread和threading這兩個模塊時,
提到要避免使用thread模塊,取而代之地使用threading模塊。

以後點明瞭緣由——
"更高級別的threading模塊更爲先進,對線程支持更爲完善,
並且使用thread模塊裏的屬性有可能會與threading出現衝突。
其次,低級別的thread模塊的同步原語不多(實際上只有一個),而threading模塊則有不少。"

閱讀完以後的整體感覺,就是threading更爲全面和強大,應該多用threading模塊,而不是thread模塊。

同時也有一點疑問,當問題解決十分簡單時(僅用thread模塊就能夠完成),
那麼此時thread相比threading還有什麼缺陷嗎?
(面對簡單問題時,我更傾向於使用thread,由於thread更爲簡單。)php

 

python的thread模塊是比較底層的模塊,python的threading模塊是對thread作了一些包裝的,能夠更加方便的被使用。python

若是是簡單應用,用thread可能更方便簡單;但真正的業務系統確定不會簡單了,因此仍是推薦threading。編程

通常來講,使用線程有兩種模式,一種是建立線程要執行的函數,把這個函數傳遞進Thread對象裏,讓它來執行;另外一種是直接從Thread繼承,建立一個新的class,把線程執行的代碼放到這個新的 class裏。多線程

Python thread實現多線程app

#-*- encoding: gb2312 -*-
import string, threading, time

def thread_main(a):
    global count, mutex
    # 得到線程名
    threadname = threading.currentThread().getName()

    for x in xrange(0, int(a)):
        # 取得鎖
        mutex.acquire()
        count = count + 1
        # 釋放鎖
        mutex.release()
        print threadname, x, count
        time.sleep(1)

def main(num):
    global count, mutex
    threads = []

    count = 1
    # 建立一個鎖
    mutex = threading.Lock()
    # 先建立線程對象
    for x in xrange(0, num):
        threads.append(threading.Thread(target=thread_main, args=(10,)))
    # 啓動全部線程
    for t in threads:
        t.start()
    # 主線程中等待全部子線程退出
    for t in threads:
        t.join()  


if __name__ == '__main__':
    num = 4
    # 建立4個線程
    main(4)

 

Python threading實現多線程函數

#-*- encoding: gb2312 -*-
import threading
import time

class Test(threading.Thread):
    def __init__(self, num):
        threading.Thread.__init__(self)
        self._run_num = num

    def run(self):
        global count, mutex
        threadname = threading.currentThread().getName()

        for x in xrange(0, int(self._run_num)):
            mutex.acquire()
            count = count + 1
            mutex.release()
            print threadname, x, count
            time.sleep(1)

if __name__ == '__main__':
    global count, mutex
    threads = []
    num = 4
    count = 1
    # 建立鎖
    mutex = threading.Lock()
    # 建立線程對象
    for x in xrange(0, num):
        threads.append(Test(10))
    # 啓動線程
    for t in threads:
        t.start()
    # 等待子線程結束
    for t in threads:
        t.join()
相關文章
相關標籤/搜索