python的多線程編程 --- thread模組

來源:互聯網
上載者:User

標籤: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模組

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.