Advertisement
rfmonk

threading_condition.py

Feb 6th, 2014
115
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.00 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(
  12.     level=logging.DEBUG,
  13.     format='%(asctime)s (%(threadName)-2s) %(message)s',
  14. )
  15.  
  16.  
  17. def consumer(cond):
  18.     """wait for the condition and use the resource"""
  19.     logging.debug('Starting consumer thread')
  20.     t = threading.currentThread()
  21.     with cond:
  22.         cond.wait()
  23.         logging.debug('Resource is available to consumer')
  24.  
  25.  
  26. def producer(cond):
  27.     """set up the resource to be used by the consumer"""
  28.     logging.debug('Starting producer thread')
  29.     with cond:
  30.         logging.debug('Making resource available')
  31.         cond.notifyAll()
  32.  
  33. condition = threading.Condition()
  34. c1 = threading.Thread(name='c1', target=consumer, args=(condition,))
  35. c2 = threading.Thread(name='c2', target=consumer, args=(condition,))
  36. p = threading.Thread(name='p', target=producer, args=(condition,))
  37.  
  38. c1.start()
  39. time.sleep(2)
  40. c2.start()
  41. time.sleep(2)
  42. p.start()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement