线程event

from threading import Thread,Event
import threading
import time,random

def conn_mysql():
    count=1
    while not event.is_set():       #需要其他线程的状态来确定下一步
        if count > 10:
            raise TimeoutError("连接超时")
        print("%s尝试第%s次连接"%(threading.current_thread(),count))
        event.wait(1)  #阻塞1秒
        count+=1
    print('%s 连接成功'%threading.current_thread())
# event.clear()  #第一个连接成功后清除了set,其他线程没法用了导致超时

def check_mysql(): print("正在检查连接") time.sleep(5) event.set() #设置此线程的状态 if __name__=='__main__': event=Event() con1=Thread(target=conn_mysql) con2 = Thread(target=conn_mysql) check=Thread(target=check_mysql) #check con1.start() time.sleep(2) con2.start() check.start()

<Thread(Thread-1, started 8568)>尝试第1次连接
<Thread(Thread-1, started 8568)>尝试第2次连接
<Thread(Thread-2, started 9144)>尝试第1次连接
正在检查连接
<Thread(Thread-1, started 8568)>尝试第3次连接
<Thread(Thread-2, started 9144)>尝试第2次连接
<Thread(Thread-1, started 8568)>尝试第4次连接
<Thread(Thread-2, started 9144)>尝试第3次连接
<Thread(Thread-1, started 8568)>尝试第5次连接
<Thread(Thread-2, started 9144)>尝试第4次连接
<Thread(Thread-1, started 8568)>尝试第6次连接
<Thread(Thread-2, started 9144)>尝试第5次连接
<Thread(Thread-1, started 8568)>尝试第7次连接
<Thread(Thread-1, started 8568)> 连接成功
<Thread(Thread-2, started 9144)> 连接成功

等于check设置了一个全局变量的值,然后其他的线程不停的再检查这个值是否符合要求

 

event.isSet():返回event的状态值;


event.wait():如果 event.isSet()==False将阻塞线程;


event.set(): 设置event的状态值为True,所有阻塞池的线程激活进入就绪状态, 等待操作系统调度;


event.clear():恢复event的状态值为False。


线程的一个关键特性是每个线程都是独立运行且状态不可预测。

如果程序中的其 他线程需要通过判断某个线程的状态来确定自己下一步的操作

,这时线程同步问题就会变得非常棘手。为了解决这些问题,我们需要使用threading库中的Event对象。

原文地址:https://www.cnblogs.com/wuxi9864/p/9998345.html