zoukankan      html  css  js  c++  java
  • 50_并发编程-线程-事件

    一、定义
        
      如果程序中的其 他线程需要通过判断某个线程的状态来确定自己下一步的操作,这时线程同步问题就会变得非常棘手。为了解决这些问题,我们需要使用threading库中的Event对象。
      事件的方法:
    1 event = Event()    # 默认状态为False
    2 event.isSet()    # 返回event的状态值
    3 event.wait()    # 如果event.isSet()==False将阻塞线程
    4 event.set()    # 设置event的状态值为True,所有阻塞池的线程激活进入就绪状态,等待操作系统调度
    5 event.clear()    # 回复event的状态为False
    事件方法

    二、实例

      首先起两个线程:
        第一个线程的用处:连接数据库,那么我这个线程需要等待一个信号,告诉我我们之间的网络是可以连通的。
        第二个线程的用处:检测与数据库之间的网络是否联通,并发送一个可联通或者不可联通的信号。
     1 from threading import Thread,Event
     2 import threading
     3 import time,random
     4 def conn_mysql():
     5     count=1
     6     while not event.is_set():
     7         if count > 3:
     8             raise TimeoutError('链接超时') #自己发起错误
     9         print('<%s>第%s次尝试链接' % (threading.current_thread().getName(), count))
    10         event.wait(0.5) #
    11         count+=1
    12     print('<%s>链接成功' %threading.current_thread().getName())
    13 
    14 
    15 def check_mysql():
    16     print('33[45m[%s]正在检查mysql33[0m' % threading.current_thread().getName())
    17     t1 = random.randint(0,3)
    18     print('>>>>',t1)
    19     time.sleep(t1)
    20     event.set()
    21 if __name__ == '__main__':
    22     event=Event()
    23     check = Thread(target=check_mysql)
    24     conn1=Thread(target=conn_mysql)
    25     conn2=Thread(target=conn_mysql)
    26 
    27     check.start()
    28     conn1.start()
    29     conn2.start()
    View Code
  • 相关阅读:
    清北学堂总结(未完待续。。。。。。。)
    洛谷p3372 线段树模版
    SPFA模版
    线段树 洛谷 p1531 I hate it(I hate it too)
    01 背包找装满方案数 洛谷 p1164 小a点菜
    01 找最大剩余体积 洛谷1049 装箱问题
    洛谷 p1880 石子合并 区间dp
    石子合并 最大值
    清北学堂入学测试d
    HTML 标记 3 —— 框架
  • 原文地址:https://www.cnblogs.com/hq82/p/9873659.html
Copyright © 2011-2022 走看看