Study Notes (30): Python Network Programming & concurrent programming -Event event

Learning immediately: https://edu.csdn.net/course/play/24458/296447?utm_source=blogtoedu

threading.Event event

 

1. Concept and function: the communication between the main thread, the operating state of another thread to another thread notifies

 

2. Use the scene:

1) wait for the server to initiate a connection client runtime, if you wait too long or try to connect too many times, suggesting that the connection failed. Only after the success of events such as server startup, will connect event

 

3.Event relevant attributes

1) Event.wait (): indicates waiting brackets can add particular latency

2) Event.set (): sends a signal to wait, waiting threads will continue to run

3) clear: Event default is False, when is set to Ture, clear that it can be reset to False

4) is_set (): determine whether the event has been set

 

4. Code

from threading import Thread,Event,currentThread
import time

#创建事件对象
event = Event()
#创建客户端函数模拟客户端连接
def client():
    n = 0
    #设置等待取消的条件函数,如果尝试连接的次数超过5次,则退出等待,因为event.wait的时间是0.5,最多等5次,需要2.5秒,而在server中沉睡了5秒,因此会等不到event.set()的执行就退出等待
    while not event.is_set():
        if n == 5:
            print('%s is failed to connect the server')
            return
        n += 1
        #这里需要注意return和break的区别,break只是跳出循环,而return是跳出函数,如果用break会使得返回连接成功的信息
        print('%s is trying to connect......'%currentThread().getName())
        print('*'*20,'%s第%s次尝试连接'%(currentThread().getName(),n),'*'*20)
        event.wait(0.5)#等待事件的发生,等待set#

    print('%s is connected'%currentThread().getName())


#创建服务端函数模拟服务器
def server():
    print("%s is trying to start"%currentThread().getName())
    time.sleep(3)
    event.set()

if __name__ == '__main__':
    for i in range(3):
        c = Thread(target=client)
        c.start()

    s = Thread(target=server)
    s.start()

Published 49 original articles · won praise 11 · views 569

Guess you like

Origin blog.csdn.net/qq_45769063/article/details/105095295