← Back to companies
[ OK ] Loaded —
[ INFO ]
$ cd
$ ls -lt
01
02
03
04
05
$ ls -lt
01
02
03
04
05
user@intervues:~/$
Implement a thread-safe counter that supports concurrent reads and updates from multiple worker threads. Design an AtomicCounter class with the following APIs:
`python class AtomicCounter: def init(self, initial_value=0): """ Initializes the counter with an initial value. """ pass
def increment(self):
"""
Increments the counter by 1 in a thread-safe manner.
"""
pass
def get(self):
"""
Returns the current value of the counter in a thread-safe manner.
"""
pass
`
AtomicCounter(10) initializes the counter with a value of 10.AtomicCounter().increment() increments the counter by 1.AtomicCounter().get() returns the current value of the counter.increment and get methods should be thread-safe.Here's a Python solution using the threading module:
`python import threading
class AtomicCounter: def init(self, initial_value=0): self.value = initial_value self.lock = threading.Lock()
def increment(self):
with self.lock:
self.value += 1
def get(self):
with self.lock:
return self.value
`
This solution uses a threading.Lock to synchronize access to the counter's value, ensuring thread safety for both increment and get operations.