day31 Event Event

Thread event Event-

Each thread is run independently and is an unpredictable state. You put a child thrown into the task thread, this task will be executed asynchronously, how to get the state to perform this task? Use Event object threading library. Object contains a flag signal provided by a thread, the thread wait until the flag is true then start execution

event.isSet() # 返回event的状态值
event.is_set()  # 返回event的状态值
event.wait()  # 等待event状态值为True
event.set()  # 设置event的状态值为True,所有阻塞的线程激活进入就绪状态,等待操作系统调度
event.clear()  # 恢复event的状态值为False

Assumptions: a thread is responsible for starting the server, start the server takes some time; another thread as a client to connect to the server must ensure that the server is started.

import time
from threading import Thread, Event


def connect_server():
    print('server ready ro started!')
    time.sleep(2)
    print('server starting....')
    event.set()  # 事件标志设为True


def connect_client():
    print('wait server start....')
    event.wait()  # 等待服务端启动,事件标识为True
    print('client starting')
    event.clear()  

    
event = Event()
server = Thread(target=connect_server)
client = Thread(target=connect_client)
server.start()
client.start()

Guess you like

Origin www.cnblogs.com/863652104kai/p/11146077.html