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.
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.