python多線程知識-實用執行個體

來源:互聯網
上載者:User

標籤:資料   int   targe   map   設定   時間   bsp   pen   建立   

python多線程使用情境:IO操作,不適合CPU密集操作型任務 1、多個線程記憶體共用2、線程同時修改同一份資料需要加鎖,mutex互斥鎖3、遞迴鎖:多把鎖,鎖中有鎖4、python多線程,同一時間只有顆CPU在執行。 啟動線程:
 1 import threading 2 def run(name) 3     print("run thread....") 4  5 #建立進程對象,target=方法名,args=(參數1,參數b,) 6 t = threading.Thread(target=run,args=(n,)) 7 #設定守護線程 8 t.setDaemon(True) 9 #啟動線程10 t.start()11 #等待線程結束12 t.jion()

 

型號量使用(線程池)

 1 import threading 2 import time 3  4 def run(n): 5     #加鎖 6     semaphore.acquire() 7     print("Look:%s"%n) 8     time.sleep(0.5) 9     #釋放鎖10     semaphore.release()11 12 if __name__ == "__main__":13     #同時准許5個線程14     semaphore = threading.BoundedSemaphore(5)15     tlist = []16     #設定多少個線程17     for i in range(33):18         t = threading.Thread(target=run,args=(i,))19         t.start()20         tlist.append(t)21     for r in tlist:22         r.jion()

 

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.