python threading/Event & Timer(3)

来源:互联网 发布:php命令行 编辑:程序博客网 时间:2024/05/19 21:16

threading.Event
  Event实现与Condition类似的功能,不过比Condition简单一点。它通过维护内部的标识符来实现线程间的同步问题。(threading.Event和.NET中的System.Threading.ManualResetEvent类实现同样的功能。)
Event.wait([timeout])
  堵塞线程,直到Event对象内部标识位被设为True或超时(如果提供了参数timeout)。
Event.set()
  将标识位设为Ture
Event.clear()
  将标识伴设为False。
Event.isSet()
  判断标识位是否为Ture。
下面使用Event来实现捉迷藏的游戏(可能用Event来实现不是很形象)

#---- Event  #---- 捉迷藏的游戏  import threading, time  class Hider(threading.Thread):      def __init__(self, cond, name):          super(Hider, self).__init__()          self.cond = cond          self.name = name      def run(self):          time.sleep(1) #确保先运行Seeker中的方法             print self.name + ': 我已经把眼睛蒙上了'          self.cond.set()          time.sleep(1)             self.cond.wait()          print self.name + ': 我找到你了 ~_~'          self.cond.set()          print self.name + ': 我赢了'  class Seeker(threading.Thread):      def __init__(self, cond, name):          super(Seeker, self).__init__()          self.cond = cond          self.name = name      def run(self):          self.cond.wait()          print self.name + ': 我已经藏好了,你快来找我吧'          self.cond.set()          time.sleep(1)          self.cond.wait()          print self.name + ': 被你找到了,哎~~~'  cond = threading.Event()  seeker = Seeker(cond, 'seeker')  hider = Hider(cond, 'hider')  seeker.start()  hider.start()  

threading.Timer
  threading.Timer是threading.Thread的子类,可以在指定时间间隔后执行某个操作。下面是Python手册上提供的一个例子:
  

def hello():      print "hello, world"  t = Timer(3, hello)  t.start() # 3秒钟之后执行hello函数。  

threading模块中还有一些常用的方法没有介绍:
threading.active_count()
threading.activeCount()
  获取当前活动的(alive)线程的个数。
threading.current_thread()
threading.currentThread()
  获取当前的线程对象(Thread object)。
threading.enumerate()
  获取当前所有活动线程的列表。
threading.settrace(func)
  设置一个跟踪函数,用于在run()执行之前被调用。
threading.setprofile(func)
  设置一个跟踪函数,用于在run()执行完毕之后调用。
  threading模块的内容很多,一篇文章很难写全,更多关于threading模块的信息,请查询Python手册 threading 模块。

原创粉丝点击