Python并发编-用Event,线程检测数据库连接的例子
Posted 空林~~清风~~~
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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()
以上是关于Python并发编-用Event,线程检测数据库连接的例子的主要内容,如果未能解决你的问题,请参考以下文章
GIL全局解释器锁死锁递归锁信号量Event事件线程Queue