Loading…
Loading…
N threads each increment a shared counter M times. Print the final counter value.
Why this is gradable. Concurrent code can legitimately produce different interleavings on every run, so this practice bank only includes problems whose correctness reduces to one deterministic final value or invariant — never a specific thread ordering. If your solution is correct, it will print the exact same output on every run, no matter how the scheduler interleaves your threads. Here, that means: the final value must equal
N * Mon every run.
Input: N = 10, M = 1000
Output: 10000
counter += 1 is not atomic — it's really "read counter, add 1, write counter back." If two threads interleave between the read and the write, one increment can be silently lost. Run the naive version enough times and you'll see the final value drift below N * M, by a different amount each time.
Wrap the read-modify-write with a threading.Lock (or your language's equivalent mutex) so only one thread can execute the increment at a time. That serializes the critical section without serializing the whole program.
Line 1: two space-separated integers, N (thread count) and M (increments per thread)
Print the final counter value.
Input (stdin)
Output
Input (stdin)
Output
Sign in to track solved problems and earn XP.