码迷,mamicode.com
首页 > 编程语言 > 详细

5.1.19 Event事件--线程之间的交互

时间:2018-06-17 11:03:03      阅读:214      评论:0      收藏:0      [点我收藏+]

标签:time   ide   while   ret   print   hide   any   event   启动   

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
View Code

 

5.1.19 Event事件--线程之间的交互

标签:time   ide   while   ret   print   hide   any   event   启动   

原文地址:https://www.cnblogs.com/beallaliu/p/9192053.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!