threading lock noblock

Solutions on MaxInterview for threading lock noblock by the best coders in the world

showing results for - "threading lock noblock"
Manuela
16 Oct 2017
1import logging
2import threading
3import time
4
5
6def lock_holder(lock):
7    logging.debug('Starting')
8    while True:
9        lock.acquire()
10        try:
11            logging.debug('Holding')
12            time.sleep(0.5)
13        finally:
14            logging.debug('Not holding')
15            lock.release()
16        time.sleep(0.5)
17
18
19def worker(lock):
20    logging.debug('Starting')
21    num_tries = 0
22    num_acquires = 0
23    while num_acquires < 3:
24        time.sleep(0.5)
25        logging.debug('Trying to acquire')
26        have_it = lock.acquire(0)
27        try:
28            num_tries += 1
29            if have_it:
30                logging.debug('Iteration %d: Acquired',
31                              num_tries)
32                num_acquires += 1
33            else:
34                logging.debug('Iteration %d: Not acquired',
35                              num_tries)
36        finally:
37            if have_it:
38                lock.release()
39    logging.debug('Done after %d iterations', num_tries)
40
41
42logging.basicConfig(
43    level=logging.DEBUG,
44    format='(%(threadName)-10s) %(message)s',
45)
46
47lock = threading.Lock()
48
49holder = threading.Thread(
50    target=lock_holder,
51    args=(lock,),
52    name='LockHolder',
53    daemon=True,
54)
55holder.start()
56
57worker = threading.Thread(
58    target=worker,
59    args=(lock,),
60    name='Worker',
61)
62worker.start()
63
similar questions
queries leading to this page
threading lock noblock