先帖他人的代码:

 
  
  1. ''''' 
  2. Created on 2012-9-4 
  3.  
  4. @author: E 
  5. ''' 
  6. #!/usr/bin/python 
  7. # -*- coding: utf-8 -*- 
  8. import threading 
  9. def DoWork(work, callback): 
  10.     def Task(): 
  11.         print 'work begin...' 
  12.         work() 
  13.         print 'work done!' 
  14.         print 'callback begin...' 
  15.         callback() 
  16.         print 'callback done!' 
  17.     t = threading.Thread(target=Task) 
  18.     t.start() 
  19. def TestWorkAndDone(): 
  20.     is_started = threading.Event() 
  21.     can_done = threading.Event() 
  22.     is_done = threading.Event() 
  23.     def Work(): 
  24.         """it's not a good idea to use huge for loop here to kill time, 
  25.              because the start and end time are not under the control. 
  26.         """ 
  27.         print '1' 
  28.         is_started.set() 
  29.         print '2' 
  30.         # block here until can_done.set() is called. 
  31.         can_done.wait(timeout=60)   # .await() in Java 
  32.         print '7' 
  33.     DoWork(work=Work, callback=lambda:is_done.set()) 
  34.     print '3' 
  35.     # block here until is_started.set() is called. 
  36.     is_started.wait(timeout=60
  37.     print '4' 
  38.     if is_started.isSet(): 
  39.         print 'SUCCESS: Work started' 
  40.     if is_done.isSet(): 
  41.         print 'FAILD: Work hasnot done' 
  42.     print '5' 
  43.     can_done.set()  # Work() is unblock. 
  44.     print '6' 
  45.     # block here until callback() is called. 
  46.     # no need to use time.sleep(60) here. 
  47.     is_done.wait(timeout=60
  48.     if is_done.isSet(): 
  49.         print 'SUCCESS: Work done' 
  50. # main 
  51. TestWorkAndDone() 

在使用线程池时,一般无工作的线程要去休眠,但是Python中的线程不会休眠,只好使用 time.sleep 来等待任务,但是有任务时又无法唤醒,自己醒时一般又没有新任务。则我们使用了 threading.Event()

首先运行上面的程序,查看结果,有一个规律就是,一旦有 wait,则程序暂停,而另一个线程在触发 set 的时候,则程序从上次wait的地方重新开始运行。

那这也就是 Event 对象的全部功能了,是一个在线程之间阻塞与解阻塞的东西,也就可以实现随时休眠,随时唤醒的功能了。