我就废话不多说,直接看代码吧!
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的锁。
以上这篇python 实现两个线程交替执行就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持我们。
时间: 2020-04-29