1、threading.Condition
创建方法:
import threading
cond=threading.Condition()
属性方法:
acquire([timeout])/release(): 调用关联的锁的相应方法。 该对象使用的是RLOCK锁。
wait([timeout]): 调用这个方法将使线程进入Condition的等待池等待通知,并释放锁。
使用前线程必须已获得锁定,否则将抛出异常。
notify(): 调用这个方法将从等待池挑选一个线程并通知,收到通知的线程将自动调用
acquire()尝试获得锁定(进入锁定池);其他线程仍然在等待池中。调用这个方法不会
释放锁定。使用前线程必须已获得锁定,否则将抛出异常。
notifyAll(): 调用这个方法将通知等待池中所有的线程,这些线程都将进入锁定池
尝试获得锁定。调用这个方法不会释放锁定。使用前线程必须已获得锁定,否则将抛出异常。
机器人对话测试代码:
cond = threading.Condition()
def robot1():
cond.acquire()
print('robot2在吗?')
cond.notify()
cond.wait()
print('我是robot1.')
def robot2():
cond.acquire()
cond.wait()
print('在,请问你是?')
cond.acquire()
cond.notify()
cond.wait()
if __name__=='__main__':
t1 = threading.Thread(target=robot1)
t2 = threading.Thread(target=robot2)
t2.start()
time.sleep(1)
t1.start()
使用该对象需要注意的两个点:
1、执行顺序,开始时的接收者应该先进入wait()状态。
2、wait()方法将在notify()和锁释放后才可以进行返回,因为notify()必须要在获得锁的情况下才能执行,所以锁释放(wait或release)必须在notify之后加上,经过测试,当另一线程调用notify时不会使得wait马上返回,只有调用了锁释放,才会生效。
测试代码的输出结果:
robot2在吗?
在,请问你是?
我是robot1.
2、threading.Event
创建方法:
import threading
event = threading.Event()
对象属性
wait():检查标志位,若为False则阻塞,等待True时返回。
clear():标志为设置为False,此时的wait()方法将阻塞。
set():标志位设置为True,wait()脱离阻塞状态向下执行。
测试代码:
event = threading.Event()
def MainThread():
i = 0
while(True):
event.wait()
print(i)
i += 1
time.sleep(1)
def ControlThread():
while(True):
print('start')
event.set()
time.sleep(5)
print('stop')
event.clear()
time.sleep(5)
if __name__=='__main__':
t1 = threading.Thread(target=MainThread)
t2 = threading.Thread(target=ControlThread)
t1.start()
t2.start()
两个线程,一个线程每隔一秒输出一个数,另一个线程每隔五秒控制一次开关变化(开变关,关变开),输出结果:
start
0
1
2
3
4
stop
start
5
6
7
8
9
stop
...