?
Solved

Monitor Not Working As Expected

Posted on 2002-06-26
4
Medium Priority
?
197 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

VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

Question has a verified solution.

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

Article by: Ivo
C# And Nullable Types Since 2.0 C# has Nullable(T) Generic Structure. The idea behind is to allow value type objects to have null values just like reference types have. This concerns scenarios where not all data sources have values (like a databa…
It was really hard time for me to get the understanding of Delegates in C#. I went through many websites and articles but I found them very clumsy. After going through those sites, I noted down the points in a easy way so here I am sharing that unde…
Monitoring a network: how to monitor network services and why? Michael Kulchisky, MCSE, MCSA, MCP, VTSP, VSP, CCSP outlines the philosophy behind service monitoring and why a handshake validation is critical in network monitoring. Software utilized …
If you’ve ever visited a web page and noticed a cool font that you really liked the look of, but couldn’t figure out which font it was so that you could use it for your own work, then this video is for you! In this Micro Tutorial, you'll learn yo…
Suggested Courses

770 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