python線程里哪種模塊比較適合
在Python中可使用的多線程模塊主要有兩個,thread和threading模塊。thread模塊提供了基本的線程和鎖的支持,建議新手不要使用。threading模塊允許創(chuàng)建和管理線程,提供了更多的同步原語。
thread模塊函數(shù):
start_new_thread(function, args[, kwargs]):啟動新的線程以執(zhí)行function,返回線程標(biāo)識。 allocate_lock():返回LockType對象。 exit():拋出SystemExit異常,如果沒有被捕獲,線程靜默退出。 LockType類型鎖對象的方法: acquire([waitflag]):無參數(shù),無條件獲得鎖,如果鎖已經(jīng)被其他線程獲取,則等待鎖被釋放。如果使用整型參數(shù),參數(shù)為0,如果鎖可獲取,則獲取且返回True,否則返回False;參數(shù)為非0,與無參數(shù)相同。 locked():返回鎖的狀態(tài),如果已經(jīng)被獲取,則返回True,否則返回False。 release():釋放鎖。只有已經(jīng)被獲取的鎖才能被釋放,不限于同一個線程。 threading模塊提供了更好的線程間的同步機(jī)制。threading模塊下有如下對象: Thread Lock RLock Condition Event Semaphore BoundedSemaphore Timer threading模塊內(nèi)還有如下的函數(shù): active_count() activeCount():返回當(dāng)前alive的線程數(shù)量 Condition():返回新的條件變量對象 current_thread() currentThread():返回當(dāng)前線程對象 enumerate():返回當(dāng)前活動的線程,不包括已經(jīng)結(jié)束和未開始的線程,包括主線程及守護(hù)線程。 settrace(func):為所有線程設(shè)置一個跟蹤函數(shù)。 setprofile(func):為所有純種設(shè)置一個profile函數(shù)。內(nèi)容擴(kuò)展:
Python線程模塊
常用參數(shù)說明
target 表示調(diào)用對象,幾子線程要執(zhí)行的的任務(wù) name 子線程的名稱 args 傳入target函數(shù)中的位置參數(shù),是一個元組,參數(shù)后必須加逗號常用的方法
Thread.star(self)啟動進(jìn)程 Thread.join(self)阻塞進(jìn)程,主線程等待 Thread.setDaemon(self,daemoic) 將子線程設(shè)置為守護(hù)線程 Thread.getName(self.name) 獲取線程名稱 Thread.setName(self.name) 設(shè)置線程名稱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表示調(diào)用對象。name是子線程的名稱。args 傳入target函數(shù)中的位置參數(shù),是個元組,參數(shù)后必須加逗號 hi_thread = Thread(target=hi) hello_thread.start() #開始執(zhí)行線程任務(wù),啟動進(jìn)程 hi_thread.start() hello_thread.join() #阻塞進(jìn)程 等到進(jìn)程運(yùn)行完成 阻塞調(diào)用,主線程進(jìn)行等待 hi_thread.join() print(hello_thread.getName()) print(hi_thread.getName()) #會默認(rèn)匹配名字 hi_thread.setName(’hiname’) print(hi_thread.getName()) print(’主線程運(yùn)行完成!’)
到此這篇關(guān)于python線程里哪種模塊比較適合的文章就介紹到這了,更多相關(guān)python線程用什么模塊好內(nèi)容請搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!
相關(guān)文章:
