python 實現兩個線程交替執行
我就廢話不多說,直接看代碼吧!
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先執行 ta.start() tb.start()
獲取對方的鎖,運行完后釋放自己的鎖
補充知識:線程同步——兩個線程輪流執行python實現
看代碼!
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()
找實習,又要回憶起操作系統的東西了。
思想:創建兩個鎖lockA和lockB。每次執行完后,鎖掉自己的鎖,并釋放對方的鎖。
初始時,若A先運行,則釋放A的鎖,鎖住B的鎖。
以上這篇python 實現兩個線程交替執行就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持好吧啦網。
相關文章: