문제

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?

도움이 되었습니까?

해결책

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top