Thread-Safe Shared Counter with Compare-and-Set

Quick Overview

Implement a counter that many threads can increment, decrement, reset and compare-and-set at the same time without losing updates. It tests read-modify-write races, mutex critical sections, atomic compare-and-set, and choosing an integer width that cannot overflow.

Thread-Safe Shared Counter with Compare-and-Set

Company: Bloomberg

Role: Software Engineer

Category: Software Engineering Fundamentals

Difficulty: easy

Interview Round: Other

Design a thread-safe shared counter that can be incremented, decremented and read from multiple threads concurrently without introducing race conditions. A naive counter implementation suffers from data corruption when multiple threads perform read-modify-write operations simultaneously. Your implementation must use proper mutex locking so that every operation appears atomic to other threads. In addition to single-value updates, the counter must support an atomic compare-and-set primitive and the ability to reset the counter to zero, all without losing updates under concurrent access. Implement a class `ThreadSafeCounter(initial: int = 0)` with the following methods: - `increment(delta: int = 1) -> int`: atomically increment the counter by `delta` (default 1) and return the new value. - `decrement(delta: int = 1) -> int`: atomically decrement the counter by `delta` (default 1) and return the new value. - `get() -> int`: return the current value of the counter. - `reset() -> int`: atomically reset the counter to 0 and return the previous value. - `compareAndSet(expected: int, new_value: int) -> bool`: atomically set the counter to `new_value` only if it currently equals `expected`. Return `True` on success and `False` otherwise. Example 1: ```text Input: ["ThreadSafeCounter", "increment", "increment", "increment", "get", "decrement", "get", "reset", "get"] [[0], [1], [1], [5], [], [2], [], [], []] Output: [null, 1, 2, 7, 7, 5, 5, 5, 0] Explanation: counter = ThreadSafeCounter(0) # initial value = 0 counter.increment(1) # -> 1 (value: 1) counter.increment(1) # -> 2 (value: 2) counter.increment(5) # -> 7 (value: 7) counter.get() # -> 7 counter.decrement(2) # -> 5 (value: 5) counter.get() # -> 5 counter.reset() # -> 5 (previous value returned, now 0) counter.get() # -> 0 ``` Example 2: ```text Input: ["ThreadSafeCounter", "increment", "compareAndSet", "get", "compareAndSet", "get", "decrement", "compareAndSet", "get"] [[10], [5], [15, 100], [], [99, 0], [], [50], [50, 50], []] Output: [null, 15, true, 100, false, 100, 50, true, 50] Explanation: counter = ThreadSafeCounter(10) # initial value = 10 counter.increment(5) # -> 15 (value: 15) counter.compareAndSet(15, 100) # -> True (value matched 15, set to 100) counter.get() # -> 100 counter.compareAndSet(99, 0) # -> False (current is 100, not 99) counter.get() # -> 100 counter.decrement(50) # -> 50 (value: 50) counter.compareAndSet(50, 50) # -> True (value matched, set to 50) counter.get() # -> 50 ``` ```hint Where updates get lost Write `self._value += delta` out as its separate read, add and write steps. Then ask which of those steps another thread must never run between, in every method, including `compareAndSet` and `reset`. ``` ### Constraints & Assumptions - The number of operations is between 1 and ${10^5}$. - `delta` is between ${-10^9}$ and ${10^9}$. - All operations may be invoked concurrently from multiple threads. ### Clarifying Questions to Ask - Which language and runtime is this for? Python with a GIL, Java and C++ give different guarantees for an unsynchronized read. - Must `get()` reflect every write that has completed, or is a slightly stale value acceptable? - In a fixed-width language, can I assume the value stays inside 64 bits, or should overflow be detected? - Is the workload write-heavy enough that one lock could become a bottleneck? ### What a Strong Answer Covers - Why an unsynchronized read-modify-write loses updates, shown with a concrete interleaving of two threads. - Which shared state the lock guards and which methods must acquire it, including whether `get()` needs it and why. - Why `compareAndSet` and `reset` stay correct when another thread writes between their read and their write. - Time and space cost per operation, and what lock contention does to throughput. - The largest value the counter can reach under the constraints and the integer type that holds it. ### Follow-up Questions - How would you implement the same API without a mutex, using an atomic compare-and-swap instruction? - With dozens of threads incrementing at a high rate, the single lock becomes a hot spot. How would you spread the writes, and what does `get()` cost afterwards? - In CPython, does the GIL make the lock unnecessary? Which operations would break without it? - How would you test that the implementation never loses an update?

Overview: Implement a counter that many threads can increment, decrement, reset and compare-and-set at the same time without losing updates. It tests read-modify-write races, mutex critical sections, atomic compare-and-set, and choosing an integer width that cannot overflow.

Bloomberg logo
Bloomberg
Nov 25, 2026
easySoftware EngineerOtherSoftware Engineering Fundamentals
0
0

Design a thread-safe shared counter that can be incremented, decremented and read from multiple threads concurrently without introducing race conditions.

A naive counter implementation suffers from data corruption when multiple threads perform read-modify-write operations simultaneously. Your implementation must use proper mutex locking so that every operation appears atomic to other threads.

In addition to single-value updates, the counter must support an atomic compare-and-set primitive and the ability to reset the counter to zero, all without losing updates under concurrent access.

Implement a class ThreadSafeCounter(initial: int = 0) with the following methods:

  • increment(delta: int = 1) -> int : atomically increment the counter by delta (default 1) and return the new value.
  • decrement(delta: int = 1) -> int : atomically decrement the counter by delta (default 1) and return the new value.
  • get() -> int : return the current value of the counter.
  • reset() -> int : atomically reset the counter to 0 and return the previous value.
  • compareAndSet(expected: int, new_value: int) -> bool : atomically set the counter to new_value only if it currently equals expected . Return True on success and False otherwise.

Example 1:

Input:
["ThreadSafeCounter", "increment", "increment", "increment", "get", "decrement", "get", "reset", "get"]
[[0],                 [1],         [1],         [5],         [],    [2],         [],    [],      []]

Output: [null, 1, 2, 7, 7, 5, 5, 5, 0]

Explanation:
counter = ThreadSafeCounter(0)        # initial value = 0
counter.increment(1)                  # -> 1     (value: 1)
counter.increment(1)                  # -> 2     (value: 2)
counter.increment(5)                  # -> 7     (value: 7)
counter.get()                         # -> 7
counter.decrement(2)                  # -> 5     (value: 5)
counter.get()                         # -> 5
counter.reset()                       # -> 5     (previous value returned, now 0)
counter.get()                         # -> 0

Example 2:

Input:
["ThreadSafeCounter", "increment", "compareAndSet", "get", "compareAndSet", "get", "decrement", "compareAndSet", "get"]
[[10],                [5],         [15, 100],       [],    [99, 0],         [],    [50],        [50, 50],        []]

Output: [null, 15, true, 100, false, 100, 50, true, 50]

Explanation:
counter = ThreadSafeCounter(10)       # initial value = 10
counter.increment(5)                  # -> 15    (value: 15)
counter.compareAndSet(15, 100)        # -> True  (value matched 15, set to 100)
counter.get()                         # -> 100
counter.compareAndSet(99, 0)          # -> False (current is 100, not 99)
counter.get()                         # -> 100
counter.decrement(50)                 # -> 50    (value: 50)
counter.compareAndSet(50, 50)         # -> True  (value matched, set to 50)
counter.get()                         # -> 50

Constraints & Assumptions

  • The number of operations is between 1 and 105{10^5} .
  • delta is between −109{-10^9} and 109{10^9} .
  • All operations may be invoked concurrently from multiple threads.

Clarifying Questions to Ask Guidance

  • Which language and runtime is this for? Python with a GIL, Java and C++ give different guarantees for an unsynchronized read.
  • Must get() reflect every write that has completed, or is a slightly stale value acceptable?
  • In a fixed-width language, can I assume the value stays inside 64 bits, or should overflow be detected?
  • Is the workload write-heavy enough that one lock could become a bottleneck?

What a Strong Answer Covers Guidance

  • Why an unsynchronized read-modify-write loses updates, shown with a concrete interleaving of two threads.
  • Which shared state the lock guards and which methods must acquire it, including whether get() needs it and why.
  • Why compareAndSet and reset stay correct when another thread writes between their read and their write.
  • Time and space cost per operation, and what lock contention does to throughput.
  • The largest value the counter can reach under the constraints and the integer type that holds it.

Follow-up Questions Guidance

  • How would you implement the same API without a mutex, using an atomic compare-and-swap instruction?
  • With dozens of threads incrementing at a high rate, the single lock becomes a hot spot. How would you spread the writes, and what does get() cost afterwards?
  • In CPython, does the GIL make the lock unnecessary? Which operations would break without it?
  • How would you test that the implementation never loses an update?