python threading模块、Event类讲解

16.2.6. Event Objects

This is one of the simplest mechanisms for communication between threads: one thread signals an event and other threads wait for it.

An event object manages an internal flag that can be set to true with the set() method and reset to false with the clear() method. The wait() method blocks until the flag is true.

class threading.Event:
The internal flag is initially false.
实例方法:

  1. set()

Set the internal flag to true. All threads waiting for it to become true are awakened. Threads that call wait() once the flag is true will not block at all.

  1. clear()

Reset the internal flag to false. Subsequently, threads calling wait() will block until set() is called to set the internal flag to true again.

  1. wait([timeout])

Block until the internal flag is true. If the internal flag is true on entry, return immediately. Otherwise, block until another thread calls set() to set the flag to true, or until the optional timeout occurs.

When the timeout argument is present and not None, it should be a floating point number specifying a timeout for the operation in seconds (or fractions thereof).

This method returns the internal flag on exit, so it will always return True except if a timeout is given and the operation times out.

翻译:Event是最简单的线程间通信机制,一个线程负责给事件发信号,其他线程等待事件。
Event类内部有一个flag标识,初始值为False。
Event类常用的三个方法有:set、clear、wait。set方法会将flag标识置为True,所有处于等待的线程将会被唤醒;clear方法会将flag重置为False;wait方法将阻塞线程,除非flag标识被置为True。

演示

# coding:gbk

import threading
import time

ev=threading.Event()

def func():
    print '%s waits event...' % threading.currentThread().getName()
    ev.wait()
    print '%s receives event...' % threading.currentThread().getName()


if __name__ == '__main__':
    t1=threading.Thread(target=func,args=())
    t2=threading.Thread(target=func,args=())

    t1.start()
    t2.start()

    time.sleep(5) #主线程休眠5秒

    print 'main thread sets event...'
    ev.set() #主线程设置事件

运行结果:

C:\Python27\python.exe E:/pythonproj/基础练习/t7.py
Thread-1 waits event...
Thread-2 waits event...
main thread sets event...
Thread-1 receives event...
 Thread-2 receives event...

Process finished with exit code 0

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

历史五千年

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值