標籤:python 線程池 線程共用
1.線程共用變數
多線程和多進程不同之處在於,多線程本身就是可以和父線程共用記憶體的,這也是為什麼其中一個線程掛掉以後,為什麼其他線程也會死掉的道理。
import threadingdef worker(l): l.append("li") l.append("and") l.append("lou")if __name__ == "__main__": l = [] l += range(1, 10) print (l) t = threading.Thread(target=worker, args=(l,)) t.start() print (l)
返回結果:
[1, 2, 3, 4, 5, 6, 7, 8, 9][1, 2, 3, 4, 5, 6, 7, 8, 9, 'li', 'and', 'lou']
2.線程池(擴充內容,瞭解即可)
通過傳入一個參數組來實現多線程,並且它的多線程是有序的,順序與參數組中的參數順序保持一致。
安裝包:
pip install threadpool
調用格式:
from threadpool import *pool = TreadPool(poolsize)requests = makeRequests(some_callable, list_of_args, callback)[pool.putRequest(req) for req in requests]pool.wait()
舉例:
import threadpooldef hello(m, n, o): print ("m = {0}, n = {1}, o = {2}".format(m, n, o))if __name__ == "__main__": #方法一: lst_vars_1 = ['1','2','3'] lst_vars_2 = ['4','5','6'] func_var = [(lst_vars_1,None), (lst_vars_2, None)] #方法二: 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()
返回結果:
m = 1, n = 2, o = 3m = 4, n = 5, o = 6
40. Python 多線程共用變數 線程池