view grok_interview/main.py @ 63:fff1b048dda6

[Postdog] Fixed a problem where string did not wrap.
author June Park <parkjune1995@gmail.com>
date Tue, 23 Dec 2025 14:00:37 -0800
parents 68fa88ac73fe
children
line wrap: on
line source

# 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()