標籤:python 多線程 編程 thread
1、使用thread模組(不推薦)
常用函數:
‘start_new_thread(function,args,kwargs=None)’:建立一個新的線程,並運行’function(args)’
‘allocate_lock()’: 建立鎖對象 Lock object
‘exit()’: 提示線程退出
Lock的函數:
‘acquire(wait=None)’: 擷取lock對象或等待wait時間
‘locked()’ 獲得lock返回true,否則返回false
‘release’ :釋放lock
例子1:
import threadfrom time import sleep,ctimedef loop0(): print ‘start loop 0"def main(): thread.start_new_thread(loop0,()) sleep(6)if __name__==‘__main__‘: main()
注意:1、雖然loop0不接受參數,但’start_new_thread’中的空tuple不能夠省略;
2、使用sleep,因為在主線程建立線程後,主線程會繼續運行直到退出,同時殺死所有的子線程,而不做任何的檢查,這也是不推薦使用thread模組的原因之一。
例子2:
import threadfrom time import sleep,ctimeloops=[4,2]def loop(nloop,nsec,lock): print ‘start loop‘,nloop,‘at:‘,ctime() lock.release()def main(): print ‘starting‘ locks=[] nloops = range(len(loops)) for i in nloops: lock=thread.allocate_lock() lock.acquire() locks.append(lock) for i in nloops: thread.start_new_thread(loop,(i,loops[i],locks[i]) for i in nloops: while locks[i].locked(): pass print ‘all done‘if __name__==‘__main__‘: main()
多個線程間可以通過共用lock,防止資源訪問的衝突
python的多線程編程 --- thread模組