同步
同步就是协同步调,按预定的先后次序进行运行。如:你说完,我再说
与同步相反的是异步:即将来就是是谁先执行不确定
同步的示例:
from threading import Thread,Lock
from time import sleep
class Task1(Thread):
def run(self):
while True:
if lock1.acquire():
print("---Task1---")
sleep(0.5)
lock2.release()
class Task2(Thread):
def run(self):
while True:
if lock2.acquire():
print("---Task2---")
sleep(0.5)
lock3.release()
class Task3(Thread):
def run(self):
while True:
if lock3.acquire():
print("---Task3---")
sleep(0.5)
lock1.release()
lock1 = Lock()
lock2 = Lock()
lock2.acquire() #让Task1执行完后再释放
lock3 = Lock()
lock3.acquire() #让Task2执行完后再释放
t1 = Task1()
t2 = Task2()
t3 = Task3()
t1.start()
t2.start()
t3.start()
'''输出结果如下:即1执行完后才能执行2,2执行完后才能执行3
---Task1---
---Task2---
---Task3---
---Task1---
---Task2---
---Task3---
---Task1---
---Task2---
---Task3---
(依次循环)
'''
网友评论