python庫學習筆記(threading庫)

來源:互聯網
上載者:User

標籤:func   odi   semaphore   sem   article   isalive   append   主程式   開始   

import threadingthreading模組裡提供的類。

  1.  Thread:表示一個線程的執行的對象。

  2.  Lock:鎖原語對象

  3.  Rlock:可重新進入鎖對象。使單線程可以再次獲得已經獲得的鎖。

  4.  Condition:條件變數對象。能讓一個線程停下來,等待其他線程滿足了“某個”條件。

  5.  Event:通用的條件變數。多個線程可以等待某個時間的發生,在事件發生後,所有的線程都被啟用。

  6.  Semaphore:為等待鎖的線程提供一個類似“等候室”的結構

  7.  Timer:與thread類似,只是它要等待一段時間後才開始運行。

threading的Thread類裡的方法。

  1.  Thread.start():開始執行線程。

  2.  Thread.join(timeout=None):阻塞主程式,直到線程結束,如果給了timeout,則最多阻塞timeout秒。

  3.  Thread.run():定義線程的功能(一般會被子類重寫)

  4.  Thread.getName():返回線程的名字。

  5.  Thread.setName():設定線程的名字。

  6.  Thread.isAlive():檢查線程是否還在執行。

  7.  Thread.isDaemon():查看線程是不是守護線程。

  8.  Thread.setDaemon():True為設定守護線程,False就不是,一定要在start()方法前調用。

執行個體:
 1 # -*- coding: utf-8 2 import threading 3 from time import ctime, sleep 4  5 def music(func): 6     for i in range(2): 7         print "I was listening to %s. %s" % (func, ctime()) 8         sleep(1) 9 10 def movie(func):11     for i in range(2):12         print "I was watching the %s. %s" % (func, ctime())13         sleep(5)14 15 #開始建立線程16 threads = []17 t1 = threading.Thread(target=music, args=(u‘愛情買賣‘,))18 threads.append(t1)19 t2 = threading.Thread(target=movie, args=(u‘阿凡達‘,))20 threads.append(t2)21 22 23 if __name__ == ‘__main__‘:24     for t in threads:25         t.start() #運行線程26     t.join() #阻塞主進程,直到第二個線程結束。27     print u‘over‘, ctime()

如果把第18行代碼放在第20行代碼後面,會出現不一樣的結果。因為第26行代碼中的t.join()只能保證迴圈中的最後一個線程運行結束,可以為每一個線程都設定一個join()方法。

1 for t in threads:2     t.join
 參考博文:

https://www.cnblogs.com/fnng/p/3670789.html

50155353

 

python庫學習筆記(threading庫)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.