Want to win a PS4? Go Premium and enter to win our High-Tech Treats giveaway. Enter to Win

x
?
Solved

Monitor Not Working As Expected

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

[Webinar] Lessons on Recovering from Petya

Skyport is working hard to help customers recover from recent attacks, like the Petya worm. This work has brought to light some important lessons. New malware attacks like this can take down your entire environment. Learn from others mistakes on how to prevent Petya like worms.

Question has a verified solution.

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

Real-time is more about the business, not the technology. In day-to-day life, to make real-time decisions like buying or investing, business needs the latest information(e.g. Gold Rate/Stock Rate). Unlike traditional days, you need not wait for a fe…
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.
This tutorial will teach you the special effect of super speed similar to the fictional character Wally West aka "The Flash" After Shake : http://www.videocopilot.net/presets/after_shake/ All lightning effects with instructions : http://www.mediaf…
In this video, Percona Solution Engineer Rick Golba discuss how (and why) you implement high availability in a database environment. To discuss how Percona Consulting can help with your design and architecture needs for your database and infrastr…

609 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