Solved

Monitor Not Working As Expected

Posted on 2002-06-26
4
192 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

Announcing the Most Valuable Experts of 2016

MVEs are more concerned with the satisfaction of those they help than with the considerable points they can earn. They are the types of people you feel privileged to call colleagues. Join us in honoring this amazing group of Experts.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
Error on Add method 1 49
C# HTTP GET method sample code 3 55
Entity Framework 7 41
Add different cell to otherwise similiar row 4 37
This article introduced a TextBox that supports transparent background.   Introduction TextBox is the most widely used control component in GUI design. Most GUI controls do not support transparent background and more or less do not have the…
This article aims to explain the working of CircularLogArchiver. This tool was designed to solve the buildup of log file in cases where systems do not support circular logging or where circular logging is not enabled
In this video I am going to show you how to back up and restore Office 365 mailboxes using CodeTwo Backup for Office 365. Learn more about the tool used in this video here: http://www.codetwo.com/backup-for-office-365/ (http://www.codetwo.com/ba…
Established in 1997, Technology Architects has become one of the most reputable technology solutions companies in the country. TA have been providing businesses with cost effective state-of-the-art solutions and unparalleled service that is designed…

815 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

15 Experts available now in Live!

Get 1:1 Help Now