So suppose I get two bank account A and B, and I need to atomically transfer money. The set up is the following: `
struct account{
int64 amount;
pthread_mutex_lock m;
}
`
here is my approach: `
bool Transfer(int from_account, int to_account, int64 amount)
{
pthread_lock(&account[from_account].m);
bool ret = false;
if(accounts[from_account].balance>=amount)
{
accounts[from_account].balance-=amount;
ret = true;
}
pthread_unlock(&account[from_account].m);
pthread_lock(&account[to_account].m);
accounts[to_account].balance+=amount;
pthread_unlock(&account[to_account].m);
return ret;
}
`
the function transfer money from from_account to to_account, return a bool, only transfer when remaining money in the account>=ammount. Is this function an okay approach? I guess it will not cause deadlock problem but doesn't it make the whole function non-atomic? So there might be race conditions? Please help me, thanks a lot.