python多线程threading事件对象event实现线程阻塞及timer时间对象

来源:互联网 发布:js获取div自定义属性 编辑:程序博客网 时间:2024/06/11 00:02

事件对象:
可以用于简单的进程之间的通信,当线程需执行其他操作时,阻塞线程
class threading.Event

1.is_set() / isSet()
2.set()
3.clear()
4.wait([timeout])

示例:

# encoding: UTF-8import threadingimport timeevent = threading.Event()def FunEvent():    print '%s -- %s start wait ...' % (time.ctime(),threading.currentThread().getName())    event.wait()    print '%s -- %s end wait ...' % (time.ctime(), threading.currentThread().getName())def bet_fun():    print '%s enter bet_fun '%time.ctime()    time.sleep(1)    print '%s out bet_fun ' % time.ctime()Th1 = threading.Thread(target=FunEvent,name="Th-1")Th2 = threading.Thread(target=FunEvent,name="Th-2")Th1.start()Th2.start()time.sleep(1)bet_fun()event.set()

结果:

Sun May 28 23:25:12 2017 -- Th-1 start wait ...Sun May 28 23:25:12 2017 -- Th-2 start wait ...Sun May 28 23:25:13 2017 enter bet_fun Sun May 28 23:25:14 2017 out bet_fun Sun May 28 23:25:14 2017 -- Th-1 end wait ... Sun May 28 23:25:14 2017 -- Th-2 end wait ...

时间对象:
class threading.Timer(interval, function, args=[], kwargs={})
interval时间,单位秒
function函数名称
方法:
1.start()
2.cancel()
例如:

def hello():    print "hello, world"t = threading.Timer(3, hello)t.start()
阅读全文
0 0