Python threading中event的使用

通过threading.Event()可以创建一个事件管理标志,该标志(event)默认为False,event对象主要有四种方法可以调用:

    event.wait(timeout=None):调用该方法的线程会被阻塞,如果设置了timeout参数,超时后,线程会停止阻塞继续执行;
    event.set():将event的标志设置为True,调用wait方法的所有线程将被唤醒;
    event.clear():将event的标志设置为False,调用wait方法的所有线程将被阻塞;

    event.isSet():判断event的标志是否为True。

下面通过一个例子来说明:

# encoding=utf8

import threading
from time import sleep

def test(n, event):
	while not event.isSet():
		print 'Thread %s is ready' % n
		sleep(1)
	event.wait()
	while event.isSet():
		print 'Thread %s is running' % n
		sleep(1)

def main():
	event = threading.Event()
	for i in xrange(0, 2):
		th = threading.Thread(target=test, args=(i, event))
		th.start()
	sleep(3)
	print '----- event is set -----'
	event.set()
	sleep(3)
	print '----- event is clear -----'
	event.clear()

if __name__ == '__main__':
	main()

运行结果如下:

Thread 0 is ready
Thread 1 is ready
Thread 1 is ready
Thread 0 is ready
Thread 1 is readyThread 0 is ready

Thread 0 is readyThread 1 is ready
 
----- event is set -----
Thread 1 is running
Thread 0 is running
Thread 0 is running
Thread 1 is running
Thread 0 is runningThread 1 is running
 ----- event is clear -----

代码解读:

    首先创建了两个子线程,并通过主线程的event对象来控制子线程什么时候开始执行(使用event.wait()方法阻塞子线程)。通过结果可以看出,在主线程sleep 3秒期间(主线程event.set()之前,此时event.isSet()为False),每个子线程都是在打印“...is ready”,并没有继续执行后面的代码。

    接着,主线程调用了event.set()后,event的标志为True,此时event.isSet()为True,所以每个线程开始打印“...is running”。

    最后,主线程又sleep 3秒后,主线程调用event.clear()方法使event的标志又变成了False,所以在主线程打印“event is clear”后,其它子线程不再打印“...is running”并退出,整个程序也结束运行。

下面再说一下event.wait(timeout)中timeout的用法,不使用timeout的时候:

# encoding=utf8

import threading


def test1(n, event):
	print 'Thread %s is ready' % n
	event.wait()
	print 'Thread %s is running' % n

def main():
	event = threading.Event()
	for i in xrange(0, 2):
		th = threading.Thread(target=test1, args=(i, event))
		th.start()

if __name__ == '__main__':
	main()

运行结果:

Thread 0 is ready
Thread 1 is ready

此时如果不手动停止程序,两个子线程将一直处于阻塞状态,永远不会打印后面的“... is running”。

下面加上timeout参数:

Thread 0 is ready
Thread 1 is ready
Thread 0 is runningThread 1 is running
此时可以看到,两个线程分别阻塞了1秒后继续执行了后面的代码,没有等待主线程的event标志变成True。
  • 42
    点赞
  • 130
    收藏
    觉得还不错? 一键收藏
  • 8
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值