python線程里哪種模塊比較適合
在Python中可使用的多線程模塊主要有兩個,thread和threading模塊。thread模塊提供了基本的線程和鎖的支持,建議新手不要使用。threading模塊允許創建和管理線程,提供了更多的同步原語。
thread模塊函數:
start_new_thread(function, args[, kwargs]):啟動新的線程以執行function,返回線程標識。 allocate_lock():返回LockType對象。 exit():拋出SystemExit異常,如果沒有被捕獲,線程靜默退出。 LockType類型鎖對象的方法: acquire([waitflag]):無參數,無條件獲得鎖,如果鎖已經被其他線程獲取,則等待鎖被釋放。如果使用整型參數,參數為0,如果鎖可獲取,則獲取且返回True,否則返回False;參數為非0,與無參數相同。 locked():返回鎖的狀態,如果已經被獲取,則返回True,否則返回False。 release():釋放鎖。只有已經被獲取的鎖才能被釋放,不限于同一個線程。 threading模塊提供了更好的線程間的同步機制。threading模塊下有如下對象: Thread Lock RLock Condition Event Semaphore BoundedSemaphore Timer threading模塊內還有如下的函數: active_count() activeCount():返回當前alive的線程數量 Condition():返回新的條件變量對象 current_thread() currentThread():返回當前線程對象 enumerate():返回當前活動的線程,不包括已經結束和未開始的線程,包括主線程及守護線程。 settrace(func):為所有線程設置一個跟蹤函數。 setprofile(func):為所有純種設置一個profile函數。內容擴展:
Python線程模塊
常用參數說明
target 表示調用對象,幾子線程要執行的的任務 name 子線程的名稱 args 傳入target函數中的位置參數,是一個元組,參數后必須加逗號常用的方法
Thread.star(self)啟動進程 Thread.join(self)阻塞進程,主線程等待 Thread.setDaemon(self,daemoic) 將子線程設置為守護線程 Thread.getName(self.name) 獲取線程名稱 Thread.setName(self.name) 設置線程名稱import timefrom threading import Thread def hello(name): print(’hello {}’.format(name)) time.sleep(3) print(’hello bye’) def hi(): print(’hi’) time.sleep(3) print(’hi bye’) if __name__ == ’__main__’: hello_thread = Thread(target=hello, args=(’wan zong’,),name=’helloname’) #target表示調用對象。name是子線程的名稱。args 傳入target函數中的位置參數,是個元組,參數后必須加逗號 hi_thread = Thread(target=hi) hello_thread.start() #開始執行線程任務,啟動進程 hi_thread.start() hello_thread.join() #阻塞進程 等到進程運行完成 阻塞調用,主線程進行等待 hi_thread.join() print(hello_thread.getName()) print(hi_thread.getName()) #會默認匹配名字 hi_thread.setName(’hiname’) print(hi_thread.getName()) print(’主線程運行完成!’)
到此這篇關于python線程里哪種模塊比較適合的文章就介紹到這了,更多相關python線程用什么模塊好內容請搜索好吧啦網以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持好吧啦網!
相關文章:
1. React+umi+typeScript創建項目的過程2. ASP.NET Core 5.0中的Host.CreateDefaultBuilder執行過程解析3. SharePoint Server 2019新特性介紹4. ASP中常用的22個FSO文件操作函數整理5. 三個不常見的 HTML5 實用新特性簡介6. ASP調用WebService轉化成JSON數據,附json.min.asp7. .Net core 的熱插拔機制的深入探索及卸載問題求救指南8. 無線標記語言(WML)基礎之WMLScript 基礎第1/2頁9. 讀大數據量的XML文件的讀取問題10. 解決ASP中http狀態跳轉返回錯誤頁的問題
