问题
I want to know why this program can have a deadlock
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);
}
Thanks.
回答1:
Say that there are two instances of the function running concurrently. The first one is transferring some amount from account A to account B, while the second is transferring some other amount from account B to account A. If it happens that the first instance acquires the lock of A and in the same time the second instance acquires the lock of B, a deadlock happens.
回答2:
as i understand it if multiple instances of a functions are running then if any of the function(withdraw,deposit) fails to reset the semaphore then other function will stop working because they can't get the semaphore.
if function guarantee to complete then deadlock may be avoided.
回答3:
I initially didn't notice there is one sem per account - and AraK deserves the accepted answer.
Just a suggestion: if the withdraw and deposit functions are not expensive, just use a unique semaphore that defines a critical section to perform any transfer. Only one transfer will happen at a given time.
sem_t *sem_tranfer; // to be created and initialized somewhere
void transfer(int from, into to, double amount) {
sem_wait(sem_transfer);
withdraw(from, amount);
deposit(to, amount);
sem_post(sem_transfer);
}
来源:https://stackoverflow.com/questions/14423418/deadlock-transfer-program