|
| 1 | +import logging |
| 2 | +import threading |
| 3 | +import time |
| 4 | + |
| 5 | +logging.basicConfig(level=logging.DEBUG, |
| 6 | + format='(%(threadName)-10s) %(message)s', |
| 7 | + ) |
| 8 | + |
| 9 | +def lock_holder(lock): |
| 10 | + logging.debug('Starting') |
| 11 | + while True: |
| 12 | + lock.acquire() |
| 13 | + try: |
| 14 | + logging.debug('Holding') |
| 15 | + time.sleep(0.5) |
| 16 | + finally: |
| 17 | + logging.debug('Not holding') |
| 18 | + lock.release() |
| 19 | + time.sleep(0.5) |
| 20 | + return |
| 21 | + |
| 22 | +def worker(lock): |
| 23 | + logging.debug('Starting') |
| 24 | + num_tries = 0 |
| 25 | + num_acquires = 0 |
| 26 | + while num_acquires < 3: |
| 27 | + time.sleep(0.5) |
| 28 | + logging.debug('Trying to acquire') |
| 29 | + have_it = lock.acquire(0) |
| 30 | + try: |
| 31 | + num_tries += 1 |
| 32 | + if have_it: |
| 33 | + logging.debug('Iteration %d: Acquired', num_tries) |
| 34 | + num_acquires += 1 |
| 35 | + else: |
| 36 | + logging.debug('Iteration %d: Not acquired', num_tries) |
| 37 | + finally: |
| 38 | + if have_it: |
| 39 | + lock.release() |
| 40 | + logging.debug('Done after %d iterations', num_tries) |
| 41 | + |
| 42 | + |
| 43 | +lock = threading.Lock() |
| 44 | + |
| 45 | +holder = threading.Thread(target=lock_holder, args=(lock,), name='LockHolder') |
| 46 | +holder.setDaemon(True) |
| 47 | +holder.start() |
| 48 | + |
| 49 | +worker = threading.Thread(target=worker, args=(lock,), name='Worker') |
| 50 | +worker.start() |
0 commit comments