DavidN
DavidN

Reputation: 111

The behavior of method/global variables inside a critical section using Mutex Class

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 :)

Upvotes: 1

Views: 440

Answers (1)

RenniePet
RenniePet

Reputation: 11658

Here's my attempt to post an answer based on your additional comments and on your indication that you considered one of my comments as helpful.

Assuming the code you're looking at is somewhat similar to this:

   public class BankAccount
   {
      private int Balance;

      private Mutex MyMutex = new Mutex();


      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;
      }
   }

then a fundamental difference between Balance and result is that Balance is an class instance variable, and there is one instance of it for each instance of the class BankAccount. Meanwhile, result is a local variable so there is one instance of result for each existing (usually zero) invocations of the BankTransferWithMutex() method.

So if there is one instance of a BankAccount object, and it is being shared by 10 threads, then the 10 threads are sharing the one instance of Balance. The result variables are associated with the invocations of the BankTransferWithMutex() method, so there is one for each current invocation - usually zero but can be up to 10.

Here's an MSDN link, although it requires clicking through a bunch to sub-topics to see the whole thing: https://msdn.microsoft.com/en-us/library/aa691160%28v=vs.71%29.aspx

Upvotes: 1

Related Questions