Python threadpool傳遞參數


threadpool模塊是一個很老的實現python線程池的模塊,pypi已經建議用multiprocessing代替它了,但是,它使用的便捷性還是征服了一批忠實用戶。

threadpool模塊實現多線程只需要如下幾行代碼:

from threadpool import *
pool = ThreadPool(poolsize)  
requests = makeRequests(some_callable, list_of_args, callback)  
[pool.putRequest(req) for req in requests]  
pool.wait()

它通過傳入一個參數組來實現多線程,並且它的多線程是有序的,順序與參數組中的參數順序保持一致。

用它傳遞參數組的例子如下:

#----------------------------------------------------------------------
def hello(m, n, o):
    """"""
    print "m = %s, n = %s, o = %s"%(m, n, o)
     
 
if __name__ == '__main__':
     
   # 方法1  
    lst_vars_1 = ['1', '2', '3']
    lst_vars_2 = ['4', '5', '6']
    func_var = [(lst_vars_1, None), (lst_vars_2, None)]
    # 方法2
    dict_vars_1 = {'m':'1', 'n':'2', 'o':'3'}
    dict_vars_2 = {'m':'4', 'n':'5', 'o':'6'}
    func_var = [(None, dict_vars_1), (None, dict_vars_2)]    
     
    pool = threadpool.ThreadPool(2)
    requests = threadpool.makeRequests(hello, func_var)
    [pool.putRequest(req) for req in requests]
    pool.wait()

  


免責聲明!

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



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