|
51
|
1 # You are required to implement a production-level code live, using concurrency. Complete within 60 minutes. Suppose you are developing a simple concurrent counter that can correctly update the count in a multi-threaded environment. The initial count value is 0. Ensure it executes in 100 threads, where each thread increments the counter by 1 every second for 10 seconds. Calculate the final count after parallel execution.
|
|
|
2 #
|
|
|
3 # Input: None
|
|
|
4 #
|
|
|
5 # Output: An integer representing the final count.
|
|
|
6 #
|
|
|
7 # Constraints:
|
|
|
8 #
|
|
|
9 # The code must use multi-threading or multi-processing techniques.
|
|
|
10 # Ensure thread safety.
|
|
|
11
|
|
|
12
|
|
|
13 # - 100 threads
|
|
|
14 # - each tread update counter by 1 everyseconds by 10 seconds
|
|
|
15 from threading import Lock
|
|
|
16 from time import sleep
|
|
|
17 from concurrent.futures import ThreadPoolExecutor
|
|
|
18
|
|
|
19
|
|
|
20 SLEEP_IN_SECONDS = 1
|
|
|
21 EXECUTION_TIME_IN_SECONDS = 3
|
|
|
22 NUMS_THREADS = 100
|
|
|
23
|
|
|
24 class Counter:
|
|
|
25
|
|
|
26 def __init__(self):
|
|
|
27 self._value = 0
|
|
|
28 self.lock = Lock()
|
|
|
29
|
|
|
30 def get(self):
|
|
|
31 return self._value
|
|
|
32
|
|
|
33 def increment(self):
|
|
|
34 with self.lock:
|
|
|
35 value = self.get()
|
|
|
36 sleep(0.01)
|
|
|
37 self._value = value + 1
|
|
|
38
|
|
|
39 def worker(counter: Counter):
|
|
|
40 for _ in range(EXECUTION_TIME_IN_SECONDS):
|
|
|
41 counter.increment()
|
|
|
42 sleep(SLEEP_IN_SECONDS)
|
|
|
43
|
|
|
44 def main():
|
|
|
45 counter = Counter()
|
|
|
46 with ThreadPoolExecutor(max_workers=NUMS_THREADS) as executor:
|
|
|
47 for _ in range(NUMS_THREADS):
|
|
|
48 executor.submit(worker, counter)
|
|
|
49 print(counter.get())
|
|
|
50
|
|
|
51 main()
|