Advertisement
rfmonk

threading_lock_nonblock.py

Feb 6th, 2014
131
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.46 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 lock_holder(lock):
  17.     logging.debug('Starting')
  18.     while True:
  19.         lock.aquire()
  20.         try:
  21.             logging.debug('Holding')
  22.             time.sleep(0.5)
  23.         finally:
  24.             logging.debug('Not holding')
  25.             lock.release()
  26.         time.sleep(0.5)
  27.     return
  28.  
  29.  
  30. def worker(lock):
  31.     logging.debug('Starting')
  32.     num_tries = 0
  33.     num_acquires = 0
  34.     while num_acquires < 3:
  35.         time.sleep(0.5)
  36.         logging.debug('Trying to acquire')
  37.         have_it = lock.acquire(0)
  38.         try:
  39.             num_tries += 1
  40.             if have_it:
  41.                 logging.debug('Iteration %d: Acquired', num_tries)
  42.                 num_acquires += 1
  43.             else:
  44.                 logging.debug('Iteration %d: Not acquired', num_tries)
  45.  
  46.         finally:
  47.             if have_it:
  48.                 lock.release()
  49.     logging.debug('Done after %d iterations', num_tries)
  50.  
  51. lock = threading.lock()
  52.  
  53. holder = threading.Thread(target=lock_holder,
  54.                           args=(lock,),
  55.                           name='LockHolder')
  56. holder.setDaemon(True)
  57. holder.start()
  58.  
  59. worker = threading.Thread(target=worker,
  60.                           args=(lock,),
  61.                           name='Worker')
  62. worker.start()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement