Concurrency 101
Thread 1 Thread 2
load R1, balance
load R2, amount load R1, balance
add R1, R2 load R2, amount
store R1, balance add R1, R2
store R1, balance
The write by Thread 1 is lost. (There are many sequences that achieve approximately the same result.)
You fix it by locking balance
so that only one thread or the other has access to it between the load and the store. Acquire a mutex on balance
at the start of the sequence and release it at the end. Consider loading amount
before loading balance
to reduce the scope of the mutex to the minimum.