Concurrent Programming Event Event

Event Event

The status of the synchronization between threads.

for example:

You put a child thrown into the task thread, this task will be executed asynchronously. How to get the state to perform this task

Solution:

  1. If we can use to get the results of asynchronous callback,
  2. Here we use another method to do: Event
Event Event

The first stage: based on polling thread to acquire state

"""a线程的任务是:开启服务器,需要3秒钟;b线程的任务是:连接服务器,直到连接成功为止"""
from threading import  Thread
import time

is_boot = False

# 开启服务器
def start_server():
    global  is_boot
    print("starting server......")
    time.sleep(3)
    print("server started!")
    is_boot = True

# 连接服务器
def connect_server():
    while True:
        if is_boot:
            print("连接服务器成功")
            break
        else:
            print("失败,服务器未启动!")
        time.sleep(0.5)


t1 = Thread(target=start_server)
t2 = Thread(target=connect_server)

t1.start()
t2.start()
starting server......
失败,服务器未启动!
失败,服务器未启动!
失败,服务器未启动!
失败,服务器未启动!
失败,服务器未启动!
失败,服务器未启动!
server started!
连接服务器成功

It can be seen that the "connected server" function, resource-consuming. In the multi-thread, and so on if we are to achieve complete server opened the moment, we then connect up, so that we can complete a one-time connection, then we use the Event event to complete

The second stage: The Event Event

from threading import  Thread,Event
import time

# 创建事件
e = Event()
print(e._flag)
# 开启服务器
def start_server():
    print("starting server......")
    time.sleep(3)
    print("server started!")
    e.set()         # 状态从False 变为 True
    print(e._flag)


# 连接服务器
def connect_server():
    e.wait()        # 等待事件从 false 变为true,当状态发生变化即可执行下面代码
    if e.is_set():
        print("连接成功")

t1 = Thread(target=start_server)
t2 = Thread(target=connect_server)
t1.start()
t2.start()
False
starting server......
server started!
True
连接成功

Guess you like

Origin www.cnblogs.com/plf-Jack/p/11140106.html