Question

In C I have:

double balance;
void deposit(double amount) 
{balance = balance +amount;}

machine language:

load R1, balance
load R2, amount
add R1, R2
store R1, balance

If the variable balance contains 500 and two threads run the procedure to deposit 300 and 200 respectively concurrently, how can this be problematic? And how do I use a concurrency mechanism to make this procedure thread safe?

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top