Advertisement
rfmonk

threading_event.py

Feb 4th, 2014
129
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.22 KB | None | 0 0
  1. #!/usr/bin/env python
  2.  
  3. # this is from The Python
  4. # Standard Library by example
  5. # ISBN13: 9780321767349
  6.  
  7. import logging
  8. import threading
  9. import time
  10.  
  11. logging.basicConfig(level=logging.DEBUG,
  12.                     format='(%(threadName)-10s) %(message)s',
  13.                     )
  14.  
  15.  
  16. def wait_for_event(e):
  17.     """Wait for the event to be set before doing anything"""
  18.     logging.debug('wait_for_event starting')
  19.     event_is_set = e.wait()
  20.     logging.debug('event set: %s', event_is_set)
  21.  
  22.  
  23. def wait_for_event_timeout(e, t):
  24.     """Wait t seconds then timeout"""
  25.     while not e.isSet():
  26.         logging.debug('wait_for_event_timeout starting')
  27.         event_is_set = e.wait(t)
  28.         logging.debug('event set: %s', event_is_set)
  29.         if event_is_set:
  30.             logging.debug('processing event')
  31.         else:
  32.             logging.debug('doing other work')
  33.  
  34. e = threading.Event()
  35. t1 = threading.Thread(name='block',
  36.                       target=wait_for_event,
  37.                       args=(e,))
  38. t1.start()
  39.  
  40. t2 = threading.Thread(name='nonblock',
  41.                       target=wait_for_event_timeout,
  42.                       args=(e, 2))
  43.  
  44. t2.start()
  45.  
  46. logging.debug('Waiting before calling Event.set()')
  47. time.sleep(3)
  48. e.set()
  49. logging.debug('Event is set')
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement