zoukankan      html  css  js  c++  java
  • 同步条件Event

    '''同步条件Event'''
    import threading
    import time
    
    class Boss(threading.Thread):
       def run(self):
          print('Boss:今晚大家加班到23:00!')
          print(event.isSet()) # False
          event.set() # ②设置event状态值为True,所有阻塞线程被激活等待操作系统调度
          time.sleep(3)
          print('Boss:22:30大家可以提前下班了!')
          event.set() # ⑤再次将event值设为True
          # print(event.isSet())
    
    class Worker(threading.Thread):
       def run(self):
          event.wait() # ①一开始本应先运行这5个线程,但event.isSet()为False,所以将被阻塞
          print('Worker:哎,又加班,烦死了!')
          time.sleep(1)
          event.clear() # ③event.clear()将event的状态值恢复为False
          event.wait() # ④又被阻塞
          print('Worker:卧槽,终于下班了,大家冲啊!')
    
    if __name__ == '__main__':
       event = threading.Event() # 生成event对象
       threads = []
    
       for i in range(5):
          threads.append(Worker())
       threads.append(Boss())
    
       for t in threads:
          t.start()
    
       for t in threads:
          t.join()
    
       print('ending...')
    '''
    event.isSet():返回event的状态值
    event.wait():如果event.isSet()==False将阻塞线程
    event.set():设置event的状态值为True,所有阻塞池的线程激活进入就绪状态,等待操作系统调度
    event.clear():恢复event的状态值为False
    '''
    # An event is a simple synchronization object;the event represents an internal flag,事件是一个简单的同步对象;事件代表一个内部标志
    # and threads can wait for the flag to be set, or set or clear the flag themselves.并且线程可以等待标志被设置,或者自己设置或清除标志
    # If the flag is set, the wait method doesn’t do anything.如果设置了标志,wait方法不会做任何事情
    # If the flag is cleared, wait will block until it becomes set again.如果标志被清除,wait将阻塞,直到它再次被设置
    # Any number of threads may wait for the same event.任意数量的线程都可以等待同一个事件
    while True: print('studying...')
  • 相关阅读:
    ASP中常用的服务器检测源代码
    dicsuzX表结构
    Flash AS3.0 加载外部资源(图片,MP3,SWF)的两种方式
    ASP快速获取远程文件大小的方法
    利用phpmyadmin修改mysql的root密码
    如何注册java程序为windows服务
    NSTimer
    ASP获得上个月、本月、下个月的第一天和最后一天的代码
    采集网页图片代码
    JS控制图片翻转代码,兼容firefox,ie,chrome等浏览器
  • 原文地址:https://www.cnblogs.com/xuewei95/p/14859930.html
Copyright © 2011-2022 走看看