Concurrency · 8 / 15 Exercise Medium

Simulated race condition

Objective

A race condition happens when several threads read and modify the same data and the result depends on the order in which they interleave. Here each thread does counter += 1 in two steps: read the value and write the value read plus 1. Real threads cannot be created in the browser, so the program simulates the situation in a deterministic way.

Instructions

  • Read n (number of threads) and a line plan of 2n letters, one per thread, that gives the order in which the steps run.
  • The first time a letter appears, that thread reads the counter and stores the value. The second time, it writes to the counter the value it read plus 1.
  • The counter starts at 0. Show Expected: n (n), Obtained: k and Lost updates: p (n minus the obtained value).
Input
2
ABAB
Output
Expected: 2
Obtained: 1
Lost updates: 1

Open the editor in full screen: the statement on the left and your code, the output and the tests on the right.

Start exercise