Example for Mutex

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • raghulvarma
    New Member
    • Oct 2007
    • 90

    Example for Mutex

    Hi,

    I am just trying to work on with mutex in Threading. I tried a sample application, could you please let me know whether this is the right way of doing a Mutex program.

    Code:
    static void Main(string[] args)
    {
    ThreadSample5_Muthex1 tt5_1 = new ThreadSample5_Muthex1();
    Thread t5_One = new Thread(tt5_1.CalculateBalance);
    tt5_1.CalculateBalance();
    t5_One.Name = "ThreadTest";
    t5_One.Start();
    Console.ReadLine();
    }
    
    class ThreadSample5_Muthex1
        {
            int amtdeposited = 0;
            public static Mutex mutex1 = new Mutex(false, "TestMutex");
            public void CalculateBalance()
            {
                int PrevAmt = 100;
                for (int j = 0; j <= 250; j++)
                {
                    mutex1.WaitOne();
                    amtdeposited = amtdeposited + j;
                }
                mutex1.ReleaseMutex();
                Console.WriteLine(amtdeposited + PrevAmt);
            }
        }
    Another doubt is that whether is it possible to return a value using a method which is called by a thread. In the above case changing
    public void CalculateBalanc e() to
    public int CalculateBalanc e(int prevamt,int amtdeposit) and return that value to the main method??
  • Banfa
    Recognized Expert Expert
    • Feb 2006
    • 9067

    #2
    A number of things, this code wont test the mutex because main runs the function and then starts the thread.

    A better test would be to start 2 or more threads all using there own instance of ThreadSample5_M utex1.

    Also you need to pass your Thread an instance of a ThreadStart class

    Code:
    Thread t5_One= new Thread(new ThreadStart(tt5_1.CalculateBalance));
    In ThreadSample5_M uthex1 there is no shared data so there is no actually need to have protected access with a mutex, however that aside.

    You should (probably) release the mutex in the same block of code that you wait for it because you must call ReleaseMutex the same number of times you call WaitOne.

    Your thread function, CalculateBalanc e, can't have a return value but even after the thread has finished the object tt5_1 still exists and can be interrogated for results.

    To make your program output clear it may be useful to output System.Threadin g.CurrentThread .Name in your WriteLine statements.

    Comment

    • raghulvarma
      New Member
      • Oct 2007
      • 90

      #3
      Banfa,

      If I have understood properly check whether I have done that correctly.
      Code:
       static void Main(string[] args)
              {
      ThreadSample5_Muthex1 tt5_1 = new ThreadSample5_Muthex1();
                  Thread t5_One = new Thread(new ThreadStart(tt5_1.CalculateBalance));
                  Thread t5_two = new Thread(new ThreadStart(tt5_1.CalculateBalance));
                  t5_One.Name = "ThreadTest ONE";
                  t5_two.Name = "ThreadTest TWO";
                  t5_One.Start();
                  t5_two.Start();
                  Console.ReadLine();
              }
      
      class ThreadSample5_Muthex1
          {
              int amtdeposited = 0;
              static Mutex mutex1 = new Mutex(false, "TestMutex");
              public void CalculateBalance()
              {
                  int PrevAmt = 100;
                  for (int j = 0; j <= 250; j++)
                  {
                      mutex1.WaitOne();
                      amtdeposited = amtdeposited + j;
                      mutex1.ReleaseMutex();
                  }
                  Console.WriteLine(Thread.CurrentThread.Name + " ~ " + (amtdeposited + PrevAmt));
              }
          }
      Last edited by Banfa; Mar 24 '11, 01:24 PM. Reason: Corrected the code tags

      Comment

      • Banfa
        Recognized Expert Expert
        • Feb 2006
        • 9067

        #4
        That is not bad have you tried running it?

        However to properly protect a piece of data, amtdeposited, in this case you need to protect both read and write accesses to it because if you only protect write accesses someone could still read it in the middle of it being changed and that could result in reading an invalid value.

        Your latest code accesses amtdeposited without protection on line 26 for the Console.WriteLi ne.

        (Sorry I could have mentioned that first time)

        Comment

        • raghulvarma
          New Member
          • Oct 2007
          • 90

          #5
          Bafna,

          I tried but I get different results when I run the same code again and again, I could Not understand what goes wrong in that. The results which I get are
          First Time :
          ThreadTest TWO ~ 62850
          ThreadTest ONE ~ 62351
          Second Time
          ThreadTest TWO ~ 31475
          ThreadTest ONE ~ 62850
          Third Time
          ThreadTest ONE ~ 39476
          ThreadTest TWO ~ 62850
          Forth Time
          ThreadTest TWO ~ 42951
          ThreadTest ONE ~ 62850
          and so on, Please could u please let me know what happens ?

          Comment

          • Banfa
            Recognized Expert Expert
            • Feb 2006
            • 9067

            #6
            Do some calculation what result do you expect?

            The value of amtdeposited for a single run of a thread is the sum of all values 0 - 250 = (250 + 0)/2*251 = 31375

            For 2 threads that would be 31375 * 2 and 100 is added for output giving 62850 which is, in all cases one of the values output.

            My guess is the 2 threads run, the one that finishes 2nd outputs 62850 because no more calculations are done after the last thread has finished. However for the thread that finishes first the value of amtdeposited is being altered by the other thread so it outputs a smaller number but a number that is >= 31475 because that is what a single run of the thread will output.

            Taking each of your results

            First Time :
            ThreadTest TWO ~ 62850
            ThreadTest ONE ~ 62351

            Thread 1 finished first but when it finish thread 2 had nearly finished.

            Second Time
            ThreadTest TWO ~ 31475
            ThreadTest ONE ~ 62850

            Thread 2 finished first when it finished thread 1 had not started.

            Third Time
            ThreadTest ONE ~ 39476
            ThreadTest TWO ~ 62850

            Thread 1 finished first when it finished thread 2 was about half way through

            Forth Time
            ThreadTest TWO ~ 42951
            ThreadTest ONE ~ 62850

            Thread 2 finished first when it finished thread 1 was about half way through

            Comment

            Working...