I am reading a book about C#, I know what a critical section is used for, however this example was on the book and it confuses me:
public bool BankTransferWithMutex(int amount)
{
bool result = false;
MyMutex.WaitOne();
if (Balance >= amount)
{
Balance -= amount;
result = true;
}
MyMutex.ReleaseMutex();
//My question is here..
return result;
}
}
My question is this, imagine there were two threads, one of them obtained access to the mutex and the bank transfer succeeded putting the result variable to true.. if the other thread came along (before the first one does the return and entered this method it would put result = false right away. Would the first thread have is result variable modified and therefore would return false despite the bank transfer being successful? Making the object state inconsistent??
Thank you for your time :)