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 模块。
- python threading/Event & Timer(3)
- python threading.Timer
- python中threading的高级函数应用解析 Lock Rlock Condition Semaphore Timer Event Semaphore对象
- python多线程threading事件对象event实现线程阻塞及timer时间对象
- Python多线程之threading Event
- Python线程之threading.Event
- python—threading.Timer【threading模块介绍03】
- python2.7 threading 模块 一 Thread Timer Event
- threading.Timer
- 【Python】threading.Event模块控制多线程
- python模块学习(threading模块中的Timer类)
- 3个Timer(System.Threading.Timer,System.Windows.Forms.Timer,System.Timers.Timer)的区别
- Python中使用threading.Event协调线程的运行
- python模块学习(threading模块中的Event类)
- System.Threading.Timer 使用
- System.Threading.Timer
- 注解:System.Threading.Timer
- System.Threading.Timer应用
- Debugging Android JNI with CheckJNI (用CheckJNI来调试Android JNI代码)
- linux安装jdk1.7 .tar.gz 版本
- 关于中断上下文
- Javascript基础(一)
- react native StatusBar的简单见解
- python threading/Event & Timer(3)
- 从jdbc中获取连接对象Connection的三种方法
- DBSCAN 算法初探
- JavaSript1
- 编码格式解析
- Spark做日志分析
- 算法基础之选择排序法
- Tensorflow--图
- 通过编程实现,统计1~n有多少个9