Advertisement
rfmonk

threading_lock.py

Feb 5th, 2014
116
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.13 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 random
  9. import threading
  10. import time
  11.  
  12. logging.basicConfig(level=logging.DEBUG,
  13.                     format='(%(threadName)-10s) %(message)s',
  14.                     )
  15.  
  16.  
  17. class Counter(object):
  18.     def __init__(self, start=0):
  19.         self.lock = threading.Lock()
  20.         self.value = start
  21.  
  22.     def increment(self):
  23.         logging.debug('Waiting for lock')
  24.         self.lock.aquire()
  25.         try:
  26.             logging.debug('Aquired lock')
  27.             self.value = self.value + 1
  28.         finally:
  29.             self.lock.release()
  30.  
  31.  
  32. def worker(c):
  33.     for i in range(2):
  34.         pause = random.random()
  35.         logging.debug('Sleeping %0.02f', pause)
  36.         time.sleep(pause)
  37.         c.increment()
  38.     logging.debug('Done')
  39.  
  40. counter = Counter()
  41. for i in range(2):
  42.     t = threading.Thread(target=worker, args=(counter,))
  43.     t.start()
  44.  
  45. logging.debug('Waiting for worker threads')
  46. main_thread = threading.currentThread()
  47. for t in threading.enumerate():
  48.     if t is not main_thread:
  49.         t.join()
  50. logging.debug('Counter: %d', counter.value)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement