2013-01-20 122 views
0

我想知道我怎麼能避免死鎖在這個程序避免死鎖 - 過程

void transfer(int from, into to, double amount) { 
    sem_t *sem_from, *sem_to; 
    sem_from=get_sem(from); //function that obtains the semaphore from bank account argument 
    sem_to=get_sem(to); 
    sem_wait(sem_from); 
    sem_wait(sem_to); 
    withdraw(from, amount); 
    deposit(to, amount); 
    sem_post(sem_to); 
    sem_post(sem_from); 
} 

感謝。

+1

http://stackoverflow.com/questions/14423418/deadlock-transfer-program – cnicutar

+0

總是測試系統調用的返回值。 –

回答

1

通過總是以相同順序獲取鎖,可以避免死鎖。

由於您的帳號是整數,因此自然會將其鎖定:首先是最小(或最大)。 (而在相反的順序釋放。)

喜歡的東西:

if (from < to) { 
    sem_one = get_sem(from); 
    sem_two = get_sem(to); 
} else if (to < from) { 
    sem_one = get_sem(to); 
    sem_two = get_sem(from); 
} else { 
    // weird self transfer, deal with it 
} 
sem_wait(sem_one); 
sem_wait(sem_two); 
// process transaction 
sem_post(sem_two); 
sem_post(sem_one); 
0

你很可能會鎖定在不同的順序。比方說,在線程1 from等於1 to等於2。在線程2 from等於2 to等於1。然後,你有這樣的事情:

時間1:線程1:鎖1個線程2:鎖2

時間2:線程1:不能LOCK2,線程2:不能鎖定1個

死鎖。