Python并发编-用Event,线程检测数据库连接的例子

  • 尝试3次连接数据库
import time
import random
from threading import Thread,Event
def connect_db(e):
    count = 0
    while count <3:
        e.wait(0.5) #状态为False的时候,等待1秒结束
        if e.is_set() == True:
            print('连接数据库')
            break
        else:
            count += 1
            print('第%s连接失败'%count)
    else:
        raise TimeoutError('数据库连接超时')
def check_web(e):
    time.sleep(random.randint(0,3))
    e.set()

e = Event()
t1 = Thread(target=connect_db,args=(e,))
t2 = Thread(target=check_web,args=(e,))
t1.start()
t2.start()
原文地址:https://www.cnblogs.com/konglinqingfeng/p/9709616.html