歡迎您光臨本站 註冊首頁

python 實現兩個線程交替執行

←手機掃碼閱讀     e36605 @ 2020-05-02 , reply:0

我就廢話不多說,直接看代碼吧!
import threading import time def 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 threading import time lockA=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的鎖。


[e36605 ] python 實現兩個線程交替執行已經有244次圍觀

http://coctec.com/docs/python/shhow-post-232585.html