diff async_multi_threads/main.py @ 69:551d9fc0a2ba

Updated wrong names.
author June Park <parkjune1995@gmail.com>
date Thu, 25 Dec 2025 20:07:46 -0800
parents
children
line wrap: on
line diff
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/async_multi_threads/main.py	Thu Dec 25 20:07:46 2025 -0800
@@ -0,0 +1,51 @@
+# 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.
+# 
+# Input: None
+# 
+# Output: An integer representing the final count.
+# 
+# Constraints:
+# 
+# The code must use multi-threading or multi-processing techniques.
+# Ensure thread safety.
+
+
+# - 100 threads
+# - each tread update counter by 1 everyseconds by 10 seconds
+from threading import Lock
+from time import sleep
+from concurrent.futures import ThreadPoolExecutor
+
+
+SLEEP_IN_SECONDS = 1
+EXECUTION_TIME_IN_SECONDS = 3
+NUMS_THREADS = 100
+
+class Counter:
+
+    def __init__(self):
+        self._value = 0
+        self.lock = Lock()
+
+    def get(self):
+        return self._value
+
+    def increment(self):
+        with self.lock:
+            value = self.get()
+            sleep(0.01)
+            self._value = value + 1
+
+def worker(counter: Counter):
+    for _ in range(EXECUTION_TIME_IN_SECONDS):
+        counter.increment()
+        sleep(SLEEP_IN_SECONDS)
+
+def main():
+    counter = Counter()
+    with ThreadPoolExecutor(max_workers=NUMS_THREADS) as executor:
+        for _ in range(NUMS_THREADS):
+            executor.submit(worker, counter)
+    print(counter.get())
+
+main()