Deadlock - Transfer Program [closed]

亡梦爱人 提交于 2019-12-25 09:44:16

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!