python threading模組多線程源碼樣本(一)__python

來源:互聯網
上載者:User

使用python模組threading來編寫多線程程式的基本思想就是, 在threading.Thread類的基礎上派生出一個子類,  將商務邏輯在該子類的run函數中實現, 建立該子類對象的線程池,並執行該子類對象的執行函數.

下面給出使用python中的threading模組進行多線程編程的一個樣本, 在源碼中,我們建立了4個線程的一個線程池和一個共用計數器, 然後讓每個線程搶佔執行時,將該計數器增1, 然後休眠. 這裡相當於給出了一個二維空間, 線程數是一維, 每個線程執行的總次數是另一維, 從下面的運行結果可以很方便地看出: 線程輪詢調度的情況.

注意這裡對count的print輸出需要包含在互斥鎖內部,否則列印結果不對.

源碼實現:

#!/usr/bin/env python#encoding: utf-8import threadingimport 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()            print threadname, x, count            count = count + 1            mutex.release()            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()

運行效果圖:


相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.