threading lock

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

showing results for - "threading lock"
Marco
20 May 2020
1import logging
2import random
3import threading
4import time
5
6
7class Counter:
8
9    def __init__(self, start=0):
10        self.lock = threading.Lock()
11        self.value = start
12
13    def increment(self):
14        logging.debug('Waiting for lock')
15        self.lock.acquire()
16        try:
17            logging.debug('Acquired lock')
18            self.value = self.value + 1
19        finally:
20            self.lock.release()
21
22
23def worker(c):
24    for i in range(2):
25        pause = random.random()
26        logging.debug('Sleeping %0.02f', pause)
27        time.sleep(pause)
28        c.increment()
29    logging.debug('Done')
30
31
32logging.basicConfig(
33    level=logging.DEBUG,
34    format='(%(threadName)-10s) %(message)s',
35)
36
37counter = Counter()
38for i in range(2):
39    t = threading.Thread(target=worker, args=(counter,))
40    t.start()
41
42logging.debug('Waiting for worker threads')
43main_thread = threading.main_thread()
44for t in threading.enumerate():
45    if t is not main_thread:
46        t.join()
47logging.debug('Counter: %d', counter.value)
48