python threading/Event & Timer(3)

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 模块。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值