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!
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.
, , . , Banker Algorithm.
, - . , , .
:
A 1, 2
B 2 1
-/, -, : , - / . , , .
- , , WaitForMultipleObjects(). API Windows, ( ) .
/ . , , , - . , concurrency.
:, . :i) Thread A Lock LEFTii) B RIGHTiii) A Lock RIGHTiv) 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 }
. , , , : (