Solved

Monitor Not Working As Expected

Posted on 2002-06-26
4
191 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
  • 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 Trending Threat Insights Every Day

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

Join & Write a Comment

Introduction Although it is an old technology, serial ports are still being used by many hardware manufacturers. If you develop applications in C#, Microsoft .NET framework has SerialPort class to communicate with the serial ports.  I needed to…
Performance in games development is paramount: every microsecond counts to be able to do everything in less than 33ms (aiming at 16ms). C# foreach statement is one of the worst performance killers, and here I explain why.
In this seventh video of the Xpdf series, we discuss and demonstrate the PDFfonts utility, which lists all the fonts used in a PDF file. It does this via a command line interface, making it suitable for use in programs, scripts, batch files — any pl…
This demo shows you how to set up the containerized NetScaler CPX with NetScaler Management and Analytics System in a non-routable Mesos/Marathon environment for use with Micro-Services applications.

759 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

Need Help in Real-Time?

Connect with top rated Experts

18 Experts available now in Live!

Get 1:1 Help Now