Skip to content
BytePatterns

Lost Updates in a Shared Counter

EasyConcurrency#race-condition#step-simulation~15m

Problem

Several threads share one counter, and each thread runs count += 1 a few times. Every increment is really three steps: read the counter into the thread's own register, add one to the register, and write the register back. You are given the number of threads and the schedule the operating system chose, as a list of thread numbers: each entry lets that thread take its next step. Every thread finishes all of its steps. Return the counter's final value, starting from 0.

Examples

Input:  threads = 2, schedule = [0, 0, 0, 1, 1, 1]
Output: 2
Why:    thread 0 finishes its increment before thread 1 reads, so nothing is lost
Input:  threads = 2, schedule = [0, 1, 0, 1, 0, 1]
Output: 1
Why:    both threads read 0, both write back 1, and one increment disappears
Input:  threads = 1, schedule = [0, 0, 0, 0, 0, 0]
Output: 2
Why:    edge case, a single thread can never race with itself

Hints

0 / 3

Stuck on the idea rather than the code? Race Conditions covers it.