How to guarantee no deadlock

I am stuck in one question in an interview.

Given two threads, and each of them has a lock, how to guarantee the absence of deadlock.

I know that it's not easy to avoid a dead end, so I'm stuck. Can someone give a hint.

Thank!

+5
source share
7 answers

The description is a bit missing, but if you put the blocking order in place (for example, if A and B are locked, never block B, if you already locked A, and you never let go of A, and B is locked), then the deadlock won Not happen.

+11
source
+3

, - . , , .

:

A 1, 2

B 2 1

+1

-/, -, : , - / . , , .

+1

- , , WaitForMultipleObjects(). API Windows, ( ) .

+1

/ . , , , - . , concurrency.

0

:

  • :
    , . :
    i) Thread A Lock LEFT
    ii) B RIGHT
    iii) A Lock RIGHT
    iv) B Lock LEFT
    --- >

    : , . , .

  • : , , , , . -

    void transferFund( Account A, Account B, Amount x)
    {
        synchronized(A)
        { 
            synchronized(B)
            {
              // do transfer update balance
            }
        }
    }                                                                                  
    

    : 1 - transferFund (A1, B1, 10); Thread 2 - transferFund (B1, A1, 20);

    : , , , . -

    if( A1.hashCode()  < B1.hashCode())
      { Lock A1 then Lock B1 }
    else
      { Lock B1 then Lock A1 }
    

. , , , : (

0
source

All Articles