python 實(shí)現(xiàn)兩個(gè)線程交替執(zhí)行
我就廢話不多說(shuō),直接看代碼吧!
import threadingimport timedef a(): while True: lockb.acquire() print(’a’) locka.release() time.sleep(0.5)def b(): while True: locka.acquire() print(’b’) lockb.release() time.sleep(0.5)if __name__ == '__main__': locka = threading.Lock() lockb = threading.Lock() ta = threading.Thread(None, a) tb = threading.Thread(None, b) locka.acquire() #保證a先執(zhí)行 ta.start() tb.start()
獲取對(duì)方的鎖,運(yùn)行完后釋放自己的鎖
補(bǔ)充知識(shí):線程同步——兩個(gè)線程輪流執(zhí)行python實(shí)現(xiàn)
看代碼!
import threadingimport timelockA=threading.Lock()lockB=threading.Lock()def printA(n): if n<0: return lockA.acquire() print('+++') lockB.release() time.sleep(0.1) printA(n-1)def printB(n): if n<0: return lockB.acquire() print('***') lockA.release() time.sleep(0.2) printB(n-1) lockB.acquire()t1=threading.Thread(target=printA,args=(10,))t2=threading.Thread(target=printB,args=(10,))t1.start()t2.start()t1.join()t2.join()
找實(shí)習(xí),又要回憶起操作系統(tǒng)的東西了。
思想:創(chuàng)建兩個(gè)鎖lockA和lockB。每次執(zhí)行完后,鎖掉自己的鎖,并釋放對(duì)方的鎖。
初始時(shí),若A先運(yùn)行,則釋放A的鎖,鎖住B的鎖。
以上這篇python 實(shí)現(xiàn)兩個(gè)線程交替執(zhí)行就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. xml中的空格之完全解說(shuō)2. ASP中解決“對(duì)象關(guān)閉時(shí),不允許操作?!钡脑幃悊?wèn)題……3. 得到XML文檔大小的方法4. ASP使用MySQL數(shù)據(jù)庫(kù)的方法5. WMLScript的語(yǔ)法基礎(chǔ)6. ASP動(dòng)態(tài)網(wǎng)頁(yè)制作技術(shù)經(jīng)驗(yàn)分享7. msxml3.dll 錯(cuò)誤 800c0019 系統(tǒng)錯(cuò)誤:-2146697191解決方法8. html小技巧之td,div標(biāo)簽里內(nèi)容不換行9. XML入門(mén)的常見(jiàn)問(wèn)題(四)10. ASP中if語(yǔ)句、select 、while循環(huán)的使用方法
