Loading…
Loading…
N threads all race to call get_instance() on a lazily-initialized singleton at (roughly) the same time. Print how many times the singleton was actually constructed.
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. A correct singleton is constructed exactly once, no matter how many threads race for it or how the scheduler interleaves them.
Input: 20
Output: 1
if instance is None: instance = Instance() has a classic race: two threads can both pass the is None check before either finishes constructing, and both end up building (and one overwriting) an instance — so the "construction count" ends up bigger than 1, non-deterministically.
This gives you both correctness (only one thread ever constructs it) and performance (most calls, after the first, never touch the lock).
1@classmethod
2def get_instance(cls):
3 if cls._instance is None:
4 with cls._lock:
5 if cls._instance is None:
6 cls._instance = cls()
7 cls._init_count += 1
8 return cls._instanceLine 1: N, the number of racing threads
Print the number of times the singleton was constructed.
Input (stdin)
Output
Input (stdin)
Output
Sign in to track solved problems and earn XP.