The problem of interlocking with the banking situation

I have a problem, I can not solve this problem

void Transfer(Account a, Account b, decimal amount) 
{
       lock (a) {
             lock (b) {
                         if (a.Balance < amount)
                         throw new InsufficientFundsExc();
                         a.Balance -= amount;
                         b.Balance += amount;
                         }
                   }
}

and the question is that "this is a transfer between bank accounts." The lock structure (...) is used against the race condition. What is the problem and what solution do you offer? CAN YOU HELP ME?

+3
source share
6 answers

if you have a transition from A to B at the same time as a transition from B to A, it can come to a standstill because you do not have a blocking order.

  • Lock thread 1
  • Lock Thread 2 B
  • Topic 1 is waiting on B
  • Topic 2 is waiting for A
  • is dead

But why the hell is this code multithreaded in the first place?

, . , .

+10

( - ), , . , a, b a, b, a.

+4

(a, b, 10.0); Transfer (b, a, 10.0); b , →

+3

CodeInChaos, . , , .

, .

Edit:
, ( , , ), , , (.. , ).

0

@RatchetFreak , . , , , .

( ) , . Daniel Chamber .

0

, . , . , : (, - ). , - , , . ", ", , - . , , , ( , ). , , " ". / , , , , " ", . : , , - , .

With a little more foresight and planning, they could find a strategy that would ensure that one of them comes out. For instance:

  • based on the desired objects:
    • eg. only when you already have a skirt can you take a shirt (at least with locks, one of the two threads contesting it should get it without breaking it into two parts), OR
  • order based on potential owners:
    • If both want to go out at the same time, whoever is born earlier can go first, or if the same one, who is taller, etc., OR
  • and again the strip, and try after a short but random interval

and etc.

0
source

All Articles