Even events
1. Definitions
Like the process, a key feature is that each thread is a separate thread running and an unpredictable state. If other threads in the program need to determine their next action by judging the state of a thread, then thread synchronization problem will become very difficult. To solve these problems, we need to use the Event object threading library. Object contains a set of threads by a signal flag that allows a thread to wait for the occurrence of certain events. In the initial case, the signal Event object flag is set to false. If there is a thread to wait for an Event object, and the sign of the Event object is false, then the thread will be blocked until the flag has been true. If one thread will signal an Event object flag is set to true, it wakes up all the threads waiting for this Event object. If a thread is waiting for a true Event has been set as the object, then it will ignore the event, continue
import time from threading import Thread, current_thread, Event event = Event() def check(): print(f'{current_thread().name}监测服务器是否开启') time.sleep(1) print(event.is_set()) event.set() print(event.is_set()) print('服务器已经开启') def connect(): print(f'{current_thread().name} 等待连接') event.wait() #event.wait(1) # 只阻塞1秒,1秒之后如果还没有进行set 直接进行下一步操作. print(f'{current_thread().name}连接成功') if __name__ == '__main__': t1 = Thread(target=check,) t2 = Thread(target=connect,) t1.start() t2.start() ####################################### Thread-1监测服务器是否开启 Thread-2 等待连接 False True 服务器已经开启 Thread-2连接成功
实例 from threading import Thread from threading import current_thread from threading import Event import time event = Event() def check(): print(f'{current_thread().name} 监测服务器是否开启...') time.sleep(4) event.set() print('服务器已经开启...') def connect(): count = 1 while not event.is_set(): if count == 4: print('连接次数过多,已断开') break event.wait(1) print(f'{current_thread().name} 尝试连接{count}次') count += 1 else: print(f'{current_thread().name} 连接成功...') t1 = Thread(target=check,) t2 = Thread(target=connect,) t1.start() t2.start() ################################ Thread-1 监测服务器是否开启... Thread-2 尝试连接1次 Thread-2 尝试连接2次 Thread-2 尝试连接3次 连接次数过多,已断开 服务器已经开启... ################################ 服务器睡3秒以下 Thread-1 监测服务器是否开启... Thread-2 尝试连接1次 Thread-2 尝试连接2次 服务器已经开启... Thread-2 尝试连接3次 Thread-2 连接成功...