天天看點

40. Python 多線程共享變量

1.線程共享變量

多線程和多程序不同之處在于,多線程本身就是可以和父線程共享記憶體的,這也是為什麼其中一個線程挂掉以後,為什麼其他線程也會死掉的道理。

import threading

def 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 threadpool

def 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 = 3
m = 4, n = 5, o = 6           

複制