python線程池

import time
# threadpool爲線程池模塊
import threadpool


def test(str):
    print str
    time.sleep(2)


if __name__ == "__main__":
    startTime = time.time()
    # 創建線程池,最多創建的線程數爲10
    pool = threadpool.ThreadPool(10)
    # 創建請求(類似於線程創建),test是目標函數,arts_list爲目標函數的參數
    requests = threadpool.makeRequests(test, args_list=['thread1', 'thread2', 'thread3', 'thread4'])
    # 將請求放入線程池中啓動
    [pool.putRequest(req) for req in requests]
    # 等待所有線程執行完畢
    pool.wait()
    endTime = time.time()
    print endTime - startTime

這裏寫圖片描述

單線程執行該方法的結果

def test(str):
    print str
    time.sleep(2)


if __name__ == "__main__":
    startTime = time.time()
    for i in range(4):
        test(str(i))
    endTime = time.time()
    print endTime - startTime

這裏寫圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章