I won't talk nonsense, just look at the code!
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() #Ensure that a is executed first
ta.start()
tb.start()
Acquire the other party's lock and release your own lock after running
Supplementary knowledge: thread synchronization-two threads take turns to execute python implementation
Look at the code!
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()
Looking for an internship, I have to remember the operating system again.
Idea: Create two locks lockA and lockB. After each execution, lock your own lock and release the other party's lock.
Initially, if A runs first, the lock of A is released and the lock of B is locked.
The above python implementation of two threads alternate execution is all the content shared by the editor, I hope to give you a reference.
Recommended Posts