event模拟数据库链接

from threading import Thread,Event,currentThread
import time
e = Event()
def conn_mysql():
    count = 1
    while e.is_set():  #没收到信号执行
        if count>3:     #超过三次,弹出错误
            raise ConnectionAbortedError('尝试链接次数太多')
        print('\33[45m%s 第%s次尝试'%(currentThread().getName(),count))
        e.wait(timeout=1)   #超时1秒链接
        count+=1   #每次链接次数+1
    print('\33[45m%s 链接到MySQL...'%(currentThread().getName()))    #收到信号执行
def check_mysql():
    print('\33[43m%s 检测到MySQL...'%(currentThread().getName()))
    time.sleep(2)
    e.set()     #在睡眠2秒后发送信号
if __name__ == '__main__':
    for i in range(3):
        t = Thread(target=conn_mysql)
        t.start()
    t = Thread(target=check_mysql)
    t.start()

  

posted @ 2017-08-30 14:58 前方、有光 阅读(...) 评论(...) 编辑 收藏