Solved

Monitor Not Working As Expected

Posted on 2002-06-26
4
194 Views
Last Modified: 2010-04-15
I have a simple program below that creates 5 instances of a worker class each worker then calls the increment function through the Thread Pool.  I have the "critical section" of code maked with monitors.

However the output is not what I would expect the threads are interleaving.  Like the monitor is not working.  I suspect monitors do not work for the thread pool??

Here is the complete code

using System;
using System.Threading ;
using System.Windows.Forms ;

class Gui : Form
{
      private MainMenu mainMenu;
       private Worker[] arrayWorkers = new Worker[5] ;
      public Gui()
       {
       
        mainMenu = new MainMenu();
          // Create The "File" Heading
        MenuItem File = mainMenu.MenuItems.Add("&File");
        File.MenuItems.Add(new MenuItem("&Start",new EventHandler(this.Start_clicked),Shortcut.CtrlX));
          this.Menu = mainMenu ;
           for ( int j = 0 ; j < 5 ; j++ )
            arrayWorkers[j] = new Worker() ;

      }
       private void Start_clicked(object sender, EventArgs e)
       {
           for ( int y = 0 ; y < 5 ; y++ )
           {
             ThreadPool.QueueUserWorkItem(new WaitCallback(arrayWorkers[y].Increment) );
          }
      }

      static void Main(string[] args)
       {
          Gui myGui = new Gui() ;
           Application.Run(myGui) ;
       }


}

class Worker
{
   public Worker(){}

   public void Increment(Object State)
   {
      int i = 0 ;
       
       Monitor.Enter(this) ;
       for ( i= 0 ; i < 100 ; i++ )
       {
         Console.WriteLine("i:" + i + " Thread Name: " +  Thread.CurrentThread.Name ) ;
          Thread.Sleep(500) ;
       }
       Monitor.Pulse(this) ;
       Monitor.Exit(this) ;
      return ;    
   }
}

0
Comment
Question by:larockd
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 2
4 Comments
 
LVL 22

Expert Comment

by:CJ_S
ID: 7113166
When using threads you can make sure that they always give different output. This is known and exactly the use of threads.

What exactly is your prolem with above code?

CJ
0
 

Author Comment

by:larockd
ID: 7114410
CJ,

My problem is that the monitor does not lock the critical section of code.

According to Microsoft on the Monitor Class

The Monitor class controls access to objects by granting a lock for an object to a single thread. Object locks provide the ability to restrict access to a block of code, commonly called a critical section. While a thread owns the lock for an object, no other thread can acquire that lock.

I would expect my output to be something along the lines of this.

Assume Two Threads: x and y

i: 0 Thread X
i: 1 Thread X
i: ...  Thread X
Thread X Finishes
Thread Y Known Can Obtain The Lock
i: 0 Thread Y
i: 1 Thread Y

----------

Instead My Output is this

i:0
i:0
i:1
i:2
i:1

Where you can clearly see the Threads Interweaving and running the critical section of code at the same time.

To summarize: The monitor is not locking the critical section of code so that other threads can't use it until the current thread is done.

Darrell

0
 

Author Comment

by:larockd
ID: 7114489
I found the problem.  I was locking on 'this' which is unique to each thread.  I needed to create an object that was shared amoung all threads.

So I created a
private static object MyLock = new Object()

in the Worker() class

and locked the monitor on that giving me the results I expected.

Darrell
0
 
LVL 1

Accepted Solution

by:
Computer101 earned 0 total points
ID: 7147190
Points refunded and question placed in PAQ

Computer101
E-E Moderator
0

Featured Post

Free Tool: Site Down Detector

Helpful to verify reports of your own downtime, or to double check a downed website you are trying to access.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Article by: Najam
Having new technologies does not mean they will completely replace old components.  Recently I had to create WCF that will be called by VB6 component.  Here I will describe what steps one should follow while doing so, please feel free to post any qu…
Exception Handling is in the core of any application that is able to dignify its name. In this article, I'll guide you through the process of writing a DRY (Don't Repeat Yourself) Exception Handling mechanism, using Aspect Oriented Programming.
In a recent question (https://www.experts-exchange.com/questions/29004105/Run-AutoHotkey-script-directly-from-Notepad.html) here at Experts Exchange, a member asked how to run an AutoHotkey script (.AHK) directly from Notepad++ (aka NPP). This video…

738 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question