Python的標準庫提供了兩個模塊:thread和threading,thread是低級模塊,threading是高級模塊,對thread進行了封裝。絕大多數情況下,我們只需要使用threading這個高級模塊。
啟動一個線程就是把一個函數傳入并創建Thread實例,然后調用start()開始執行:
import time,threadingdef loop(): 輸出結果:thread MainThread is running… thread LoopThread is running… thread LoopThread >>> 1 thread LoopThread >>> 2 thread LoopThread >>> 3 thread LoopThread >>> 4 thread LoopThread >>> 5 thread LoopThread ended. thread MainThread ended.
由于任何進程默認就會啟動一個線程,我們把該線程稱為主線程,主線程又可以啟動新的線程,Python的threading模塊有個current_thread()函數,它永遠返回當前線程的實例。主線程實例的名字叫MainThread,子線程的名字在創建時指定,我們用LoopThread命名子線程。名字僅僅在打印時用來顯示,完全沒有其他意義,如果不起名字Python就自動給線程命名為Thread-1,Thread-2……
>
starting writer at: Mon Mar 06 16:34:51 2017 add for Q… size now= 1 starting reader at: Mon Mar 06 16:34:51 2017 sub from Q… size now= 0 add for Q… size now= 1 sub from Q… size now= 0 add for Q… size now= 1 add for Q… size now= 2 writer finished at: Mon Mar 06 16:34:57 2017 sub from Q… size now= 1 sub from Q… size now= 0 reader finished at: Mon Mar 06 16:35:06 2017 all DONE
參考文獻: http://www.tuicool.com/articles/vQQNbiz
新聞熱點
疑難解答