1. 程式人生 > >Python threadpool傳遞參數

Python threadpool傳遞參數

lin 傳遞參數 ber quest class 數組 sin multi hello

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

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

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

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

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

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 #---------------------------------------------------------------------- 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()

  

Python threadpool傳遞參數