40. Python 多線程共用變數 線程池

來源:互聯網
上載者:User

標籤: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 多線程共用變數 線程池

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.