event=Event()
event.isSet() # 返回event的状态值 True False
event.wait() #等待其他线程发出event.set()后才继续往下执行 event.isSet() == False 将阻塞线程
event.wait(3) #如果超过3秒,即使没有收到event.set()也会继续往下执行
event.set() # 设置event的状态值为True, 所有阻塞池的线程激活进入就绪状态,等待操作系统调度
event.clear() # 恢复event的状态值为False
模拟多个客户端连接服务器端,检测服务器是否正常运行? 服务器要先起来,客户端才可以连接。
from threading import Event from threading import Thread from threading import current_thread import time event = Event() def conn(): print(‘is connecting ......‘) n = 0 while not event.is_set(): if n == 5: print(‘%s try too many count!‘ % current_thread().getName()) return event.wait(1) print(‘%s try %s‘ % (current_thread().getName(), n)) n += 1 print(‘connected‘) def check(): print(‘server is starting ......‘) time.sleep(5) print(‘server is started!‘) event.set() if __name__ == ‘__main__‘: conn1 = Thread(target=conn) conn2 = Thread(target=conn) conn3 = Thread(target=conn) check1 = Thread(target=check) conn1.start() conn2.start() conn3.start() check1.start()
运行结果: 可设置服务器启动时间,和连接时间和重试试数,观察不同的结果
is connecting ...... is connecting ...... is connecting ...... server is starting ...... Thread-1 try 0 Thread-3 try 0 Thread-2 try 0 Thread-1 try 1 Thread-3 try 1 Thread-2 try 1 Thread-3 try 2 Thread-2 try 2 Thread-1 try 2 Thread-3 try 3 Thread-1 try 3 Thread-2 try 3 server is started! Thread-2 try 4 connected Thread-1 try 4 connected Thread-3 try 4 connected
原文:https://www.cnblogs.com/beallaliu/p/9192053.html