The modules described in this chapter provide support for concurrent execution of code. The appropriate choice of tool will depend on the task to be executed (CPU bound vs IO bound) and preferred style of development (event
driven cooperative multitasking vs preemptive multitasking).python
threading是一個基於_thread(python2中的thread)高級模塊,和queue模塊也有關係。在_thread模塊缺失時能夠使用dummy_threading模塊。多線程
在這個模塊中定義了一些經常使用的方法:併發
threading.active_count() : 返回Thread對象的當前存活數。等同於enumerate()方法返回的list的長度app
threading.current_thread() :返回當前Thread對象,和調用者的ide
threading.get_ident() : 返回 當前thread 標識,非0整數,沒有意義。函數
threading.enumerate() : 返回一個包含全部存活的thread對象的list,不包括終止了的和沒有啓動的線程。oop
threading.main_thread() : 返回 main thread對象。this
線程的私有數據,要管理thread-local數據,須要建立一個 local實例或者local的子類實例來保存屬性。spa
mydata = threading.local() mydata.x = 1 class threading.local
Thread類表示在一個獨立的線程裏運行的任務,有兩種方式定義這個任務:傳遞一個可調用的對象給生成器,或者在子類中重寫run()方法,即不傳遞可調用對象,則執行類的run方法。線程
建立完成以後,調用start()方法來啓動該線程,啓動以後則認爲線程是 alive的,除非run()方法終止或者拋出異常。
能夠調用一個線程的join()方法,該方法會阻塞調用線程(主線程)直到被調用線程的join()方法中止。
線程能夠有名字,能夠在建立過程當中傳遞,也能夠經過name屬性來讀取和修改。
線程能夠標識爲 daemon線程,表示整個python程序退出以後,daemon線程仍保持。
class threading.Thread(group=None, target=None, name=None, args=(), kwargs={}, *, daemon=None)
該生成器應該帶關鍵字參數調用,參數以下:
group: 爲None,做爲保留,後續ThreadGroup類被建立後擴展使用
target: 傳遞一個被run()方法調用的可調用對象。
name: 線程名字,默認是Thread-N
args: 是調用對象的參數,爲元組對象(),只有一個參數時:(a,)
kwargs: 是一個關鍵字參數對象,默認是dict {}
daemon: 默認爲None,若是爲None則繼承建立的線程的該屬性。
start(): 啓動線程任務
run(): 啓動線程以後執行的任務,能夠在子類中重寫這個函數。
join(): 等待線程結束,calling線程一直阻塞直到調用的join()方法中止,或者超時,能夠經過is_alive來斷定是超時或者正常中止和異常退出。在start以前或者進入一個死循環會致使線程超時
getName()
setName()
ident(): 線程標識。
is_alive(): 確認線程是否存活
daemon: 布爾值,標識線程是不是一個daemon線程(True 是),必須在啓動前設置該值。
isDaemon()
setDaemon()
class threading.Lock
done