2. Python中的多線程相關(guān)模塊和方法
Python中提供幾個用于多線程編程的模塊,包括thread,threading和Queue等
thread模塊提供了基本的線程和鎖的支持,除產(chǎn)生線程外,也提供基本的同步數(shù)據(jù)結(jié)構(gòu)鎖對象,其中包括:
start_new_thread(function, args kwargs=None) 產(chǎn)生一個新的線程來運(yùn)行給定函數(shù)
allocate_lock() 分配一個LockType類型的鎖對象
exit() 讓線程退出
acquire(wait=None) 嘗試獲取鎖對象
locked() 如果獲取了鎖對象返回TRUE,否則返回FALSE
release() 釋放鎖
threading提供了更高級別,功能更強(qiáng)的線程管理功能
Thread類 表示一個線程的執(zhí)行的對象
Lock 鎖原語對象
RLock 可重入鎖對象,使單線程可以再次獲得已經(jīng)獲取鎖
queue模塊允許用戶創(chuàng)建一個可以用于多個線程之間共享數(shù)據(jù)的隊(duì)列數(shù)據(jù)結(jié)構(gòu)
可用于進(jìn)程間的通訊,讓各個線程之間共享數(shù)據(jù)
模塊函數(shù)queue(size) 創(chuàng)建一個大小為size的Queue對象
queue對象函數(shù) qsize() 返回隊(duì)列大小
empty() 隊(duì)列為空返回True,否則返回False
put(item, block=0) 把ITEM放到隊(duì)列中,block不為0,函數(shù)會一直阻塞到隊(duì)列中
get(block=0) 從隊(duì)列中取一個對象,若果給block,函數(shù)會一直阻塞到隊(duì)列中有對象為止
3.示例
目前Python的lib中對多線程編程提供兩種啟動方法,一種是比較基本的thread模塊中start_new_thread方法,在線程中運(yùn)行一個函數(shù), 另一種是使用集成threading模塊的線程對象Thread類。
目前所用到的,是舊版本中調(diào)用thread模塊中的start_new_thread()函數(shù)來產(chǎn)生新的線程
相比而言,thread.start_new_thread(function,(args[,kwargs]))實(shí)現(xiàn)機(jī)制其實(shí)與C更為類似,其中function參數(shù)是將要調(diào)用的線程函數(shù);(args[,kwargs])是將傳遞給待創(chuàng)建線程函數(shù)的參數(shù)組成的元組類型,其中kwargs是可選的參數(shù)。新創(chuàng)建的線程結(jié)束一般依靠線程函數(shù)的執(zhí)行結(jié)束自動退出,或者在線程函數(shù)中調(diào)用thread.exit()拋出SystemExit exception,達(dá)到線程退出的目的。
print "=======================thread.start_new_thread啟動線程=============" import thread #Python的線程sleep方法并不是在thread模塊中,反而是在time模塊下 import time def inthread(no,interval): count=0 while count<10: print "Thread-%d,休眠間隔:%d,current Time:%s"%(no,interval,time.ctime()) #使當(dāng)前線程休眠指定時間,interval為浮點(diǎn)型的秒數(shù),不同于Java中的整形毫秒數(shù) time.sleep(interval) #Python不像大多數(shù)高級語言一樣支持++操作符,只能用+=實(shí)現(xiàn) count+=1 else: print "Thread-%d is over"%no #可以等待線程被PVM回收,或主動調(diào)用exit或exit_thread方法結(jié)束線程 thread.exit_thread() #使用start_new_thread函數(shù)可以簡單的啟動一個線程,第一個參數(shù)指定線程中執(zhí)行的函數(shù),第二個參數(shù)為元組型的傳遞給指定函數(shù)的參數(shù)值 thread.start_new_thread(inthread,(1,2)) #線程執(zhí)行時必須添加這一行,并且sleep的時間必須足夠使線程結(jié)束,如本例 #如果休眠時間改為20,將可能會拋出異常 time.sleep(30) '''
使用這種方法啟動線程時,有可能出現(xiàn)異常
Unhandled exception in thread started by Error in sys.excepthook: Original exception was:
解決:啟動線程之后,須確保主線程等待所有子線程返回結(jié)果后再退出,如果主線程比子線程早結(jié)束,無論其子線程是否是后臺線程,都將會中斷,拋出這個異常
若沒有響應(yīng)阻塞等待,為避免主線程提前退出,必須調(diào)用time.sleep使主線程休眠足夠長的時間,另外也可以采用加鎖機(jī)制來避免類似情況,通過在啟動線程的時候,給每個線程都加了一把鎖,直到線程運(yùn)行介紹,再釋放這個鎖。同時在Python的main線程中用一個while循環(huán)來不停的判斷每個線程鎖已釋放。
import thread; from time import sleep,ctime; from random import choice #The first param means the thread number #The second param means how long it sleep #The third param means the Lock def loop(nloop,sec,lock): print "Thread ",nloop," start and will sleep ",sec; sleep(sec); print "Thread ",nloop," end ",sec; lock.release(); def main(): seconds=[4,2]; locks=[]; for i in range(len(seconds)) : lock=thread.allocate_lock(); lock.acquire(); locks.append(lock); print "main Thread begins:",ctime(); for i,lock in enumerate(locks): thread.start_new_thread(loop,(i,choice(seconds),lock)); for lock in locks : while lock.locked() : pass; print "main Thread ends:",ctime(); if __name__=="__main__" : main();
很多介紹說在新python版本中推薦使用Threading模塊,目前暫沒有應(yīng)用到。。
聲明:本網(wǎng)頁內(nèi)容旨在傳播知識,若有侵權(quán)等問題請及時與本網(wǎng)聯(lián)系,我們將在第一時間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com