先帖他人的代码:
- '''''
- Created on 2012-9-4
- @author: E
- '''
- #!/usr/bin/python
- # -*- coding: utf-8 -*-
- import threading
- def DoWork(work, callback):
- def Task():
- print 'work begin...'
- work()
- print 'work done!'
- print 'callback begin...'
- callback()
- print 'callback done!'
- t = threading.Thread(target=Task)
- t.start()
- def TestWorkAndDone():
- is_started = threading.Event()
- can_done = threading.Event()
- is_done = threading.Event()
- def Work():
- """it's not a good idea to use huge for loop here to kill time,
- because the start and end time are not under the control.
- """
- print '1'
- is_started.set()
- print '2'
- # block here until can_done.set() is called.
- can_done.wait(timeout=60) # .await() in Java
- print '7'
- DoWork(work=Work, callback=lambda:is_done.set())
- print '3'
- # block here until is_started.set() is called.
- is_started.wait(timeout=60)
- print '4'
- if is_started.isSet():
- print 'SUCCESS: Work started'
- if is_done.isSet():
- print 'FAILD: Work hasnot done'
- print '5'
- can_done.set() # Work() is unblock.
- print '6'
- # block here until callback() is called.
- # no need to use time.sleep(60) here.
- is_done.wait(timeout=60)
- if is_done.isSet():
- print 'SUCCESS: Work done'
- # main
- TestWorkAndDone()
在使用线程池时,一般无工作的线程要去休眠,但是Python中的线程不会休眠,只好使用 time.sleep 来等待任务,但是有任务时又无法唤醒,自己醒时一般又没有新任务。则我们使用了 threading.Event()
首先运行上面的程序,查看结果,有一个规律就是,一旦有 wait,则程序暂停,而另一个线程在触发 set 的时候,则程序从上次wait的地方重新开始运行。
那这也就是 Event 对象的全部功能了,是一个在线程之间阻塞与解阻塞的东西,也就可以实现随时休眠,随时唤醒的功能了。
转载于:https://blog.51cto.com/eachcan/982431