Given no other measures why is the following code a bad idea in a distributed sy
ID: 3640401 • Letter: G
Question
Given no other measures why is the following code a bad idea in a distributed system in whichmultiple requests can be initiated simultaneously?1 struct Account {
2 long long value;
3 } ;
4
5 enum AccOps { DEPOSIT , DEBIT , VALUE };
6
7 i n t
8 handleRequest ( struct Account * ac , enum AccOps op , lon g lon g *v )
9 {
10 int rc = 1 ;
11
12 i f ( v==0) { rc = -1; goto done ; }
13
14 swi t c h ( op ) {
15 case DEPOSIT :
16 if (*v>0) ac->value += *v ; else rc = -1;
17 break ;
18 case DEBIT :
19 i f (* v>0) ac->value -= *v ; else rc = -1;
20 break ;
21 case VALUE:
22 *v = ac->value ;
23 break ;
24 default :
25 rc = -1;
26 }
27
28 done :
29 return rc ;
30 }
Explanation / Answer
This code operates the balance of an account by pulling out the value, doing the change, and then putting the value back in. If it is operating on a distributed system where multiple requests can be done at the same time, it would be possible for a second person to pull the request immediately after you did, and then update it immediately after you do, which would erase your action. For example, if a retailer is trying to make a $3 withdrawal for the burger you purchased, and your employer is trying to make a $5 deposit (Pretty crummy wage, sorry) Balance = $10 Retailer pulls the balance ($10) Employer pulls the balance ($10) Retailer subtracts 3 to their number and posts the new balance ($7) Employer adds $5 to their number and posts the new balance ($15) The Retailers debit on the account was basically erased. This would turn out very badly for the bank. To prevent this you must use a locking mechanism that is set before a transaction starts, and then cleared when the transaction finishes.
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.