Click here to Skip to main content
Click here to Skip to main content

Thread Sychronization using monitors

, 31 Oct 2001 CPOL
Rate this:
Please Sign up or sign in to vote.
Introduction to using the Monitor class for accessing shared resources from multiple threads

Introduction

Once you start doing multi-threaded programs, the first thing you know, you are faced with the problem of multiple threads accessing the same resource. Sometimes this can result in depressing errors. Like when two threads try to open the same file. Or when one thread is writing to a file and the other thread is trying to truncate it. You might get program crashes which is bad, and you might get a corrupted file, which is considerably worse.

The .NET framework gives us the Monitor class as one solution, but there are other methods too like settable events. This article will cover the usage of the Monitor class for thread synchronization. But first, I'd like to try and simulate a thread-synchronization problem. Take a look at the below program. There are two threads. Both of them increment the same int resource x. I've simulated the processing by using two for loops and a Sleep. So basically we expect to see 20 numbers [from 0 to 19 in that order] displayed on screen

Program Listing

#using <mscorlib.dll>

using namespace System;
using namespace System::Threading;

__gc class AddThread
{
public:
    int x;
    void Add1();
    AddThread();
    Thread *t1,*t2;	
};

int wmain(void)
{
    AddThread *a=new AddThread();
    return 0;
}

AddThread::AddThread()
{
    x=0;
    t1=new Thread(new ThreadStart(this,&AddThread::Add1));
    t2=new Thread(new ThreadStart(this,&AddThread::Add1));
    t1->Name="Thread 1";
    t2->Name="Thread 2";
    t1->Start();
    t2->Start();
}

void AddThread::Add1()
{
    for (int j=0;j<10;j++)
    {

        for (int t=0;t<5000;t++)
            x++;

        //using Sleep to simulate a real-case scenario
        //where heavy time-consuming calculations might be done		
        Thread::Sleep(5);
		
        for (int t=0;t<5000;t++)
            x--;

        Console::WriteLine("{0}.....{1} has incremented x",
            __box(x++),Thread::CurrentThread->Name);			
    }
}

Now compile and run that program. You might have expected to see numbers 0 to 19 shown on screen. Well, this is what I got. I presume you'll get something similar depending on your processor's speed and its current load.

Output

D:\MyProjs\mcppthreadsync01\Debug>mcppthreadsync01.exe
5000.....Thread 1 has incremented x
5001.....Thread 2 has incremented x
5002.....Thread 1 has incremented x
5003.....Thread 2 has incremented x
5004.....Thread 1 has incremented x
5005.....Thread 2 has incremented x
5006.....Thread 1 has incremented x
5007.....Thread 2 has incremented x
5008.....Thread 1 has incremented x
5009.....Thread 2 has incremented x
5010.....Thread 1 has incremented x
5011.....Thread 2 has incremented x
5012.....Thread 2 has incremented x
5013.....Thread 1 has incremented x
5014.....Thread 2 has incremented x
15.....Thread 1 has incremented x
5016.....Thread 2 has incremented x
5017.....Thread 1 has incremented x
5018.....Thread 2 has incremented x
19.....Thread 1 has incremented x

D:\MyProjs\mcppthreadsync01\Debug>

Hmmm. Not what we wanted. Not at all! The whole problem is that one of the threads is doing something with x, just as the other thread is accessing it. So, how do we prevent that?

Well, that's where the Monitor class comes into play. We can use the Monitor class to lock a resource so that no other thread can access it and then release it after use.

I have modified the Add1 member function as follows

void AddThread::Add1()
{
    for (int j=0;j<10;j++)
    {
        Monitor::Enter(this);    //added this line	
        for (int t=0;t<5000;t++)
            x++;
		
        Thread::Sleep(5);
		
        for (int t=0;t<5000;t++)
            x--;
        Console::WriteLine("{0}.....{1} has incremented x",
            __box(x++),Thread::CurrentThread->Name);				

        Monitor::Exit(this);    //added this line

    }
}

Now compile and run the program.

Output

D:\MyProjs\mcppthreadsync01\Debug>mcppthreadsync01.exe
0.....Thread 1 has incremented x
1.....Thread 2 has incremented x
2.....Thread 1 has incremented x
3.....Thread 2 has incremented x
4.....Thread 1 has incremented x
5.....Thread 2 has incremented x
6.....Thread 1 has incremented x
7.....Thread 2 has incremented x
8.....Thread 1 has incremented x
9.....Thread 2 has incremented x
10.....Thread 1 has incremented x
11.....Thread 2 has incremented x
12.....Thread 1 has incremented x
13.....Thread 2 has incremented x
14.....Thread 1 has incremented x
15.....Thread 2 has incremented x
16.....Thread 1 has incremented x
17.....Thread 2 has incremented x
18.....Thread 1 has incremented x
19.....Thread 2 has incremented x

D:\MyProjs\mcppthreadsync01\Debug>

Ah! That's what we wanted. Hmm, let's take a look at how that came about. We added the following two lines.

Monitor::Enter(this);

and

Monitor::Exit(this);

Enter will block [means it just waits there] if some other thread has locked the resource [in our case, we pass the this pointer]. If the object is free, then Enter will obtain a monitor lock on that object.

Exit will release the monitor lock on that resource. They are both static member functions of the Monitor class.

From the same thread you can invoke Enter more than once and it won't block; but you must make sure that there are as many Exit calls as there were Enter calls.

In some cases blocking would be undesirable. In that case, you can use an alternate call called TryEnter. It has three overloads. The overload we are interested in is 

public: static bool TryEnter(Object* obj);

This won't block but will return true if the lock was obtained and false if the resource was already locked. There are other overloads for TryEnter which allow us to block for a specified time interval. You can look up Monitor::TryEnter in the .NET Framework SDK documentation.

Let's say we want Thread 2 to finish the first six numbers before we want thread 1 to start its work. Here we can make use of the Wait and Pulse member functions.

I have modified the Add1 function again :-

void AddThread::Add1()
{
    for (int j=0;j<10;j++)
    {
        Monitor::Enter(this);				
		
        //<newly_added_block>
        if(Thread::CurrentThread->Name->Equals("Thread 1"))
        {
            if(x<5)
                Monitor::Wait(this);
        }
        else
        {
            if(x>4)
                Monitor::Pulse(this);
        }
        //</newly_added_block>

        for (int t=0;t<5000;t++)
            x++;
		
        Thread::Sleep(5);
		
        for (int t=0;t<5000;t++)
            x--;
        Console::WriteLine("{0}.....{1} has incremented x",
            __box(x++),Thread::CurrentThread->Name);				
        Monitor::Exit(this);		

    }
}

What Wait does is that it frees the monitor but indicates to the CLR that it expects to get the monitor back when its free again. And Pulse indicates to the CLR that a change in state has occurred which might free one of the waiting threads. The CLR keeps track of all waiting threads which it frees in the order in which they invoked Wait.

Now compile and run the program. You'll get this :-

D:\MyProjs\mcppthreadsync01\Debug>mcppthreadsync01.exe
0.....Thread 2 has incremented x
1.....Thread 2 has incremented x
2.....Thread 2 has incremented x
3.....Thread 2 has incremented x
4.....Thread 2 has incremented x
5.....Thread 2 has incremented x
6.....Thread 1 has incremented x
7.....Thread 2 has incremented x
8.....Thread 1 has incremented x
9.....Thread 2 has incremented x
10.....Thread 1 has incremented x
11.....Thread 2 has incremented x
12.....Thread 1 has incremented x
13.....Thread 2 has incremented x
14.....Thread 1 has incremented x
15.....Thread 1 has incremented x
16.....Thread 1 has incremented x
17.....Thread 1 has incremented x
18.....Thread 1 has incremented x
19.....Thread 1 has incremented x

There is also a PulseAll function that notifies all waiting threads. The thread that invoked PulseAll releases the lock. Remember that Pulse, PulseAll and Wait must only be invoked from within a synchronized block of code.

Thank You

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Nish Sivakumar

United States United States
Nish is a real nice guy who has been writing code since 1990 when he first got his hands on an 8088 with 640 KB RAM. Originally from sunny Trivandrum in India, he has been living in various places over the past few years and often thinks it’s time he settled down somewhere.
 
Nish has been a Microsoft Visual C++ MVP since October, 2002 - awfully nice of Microsoft, he thinks. He maintains an MVP tips and tricks web site - www.voidnish.com where you can find a consolidated list of his articles, writings and ideas on VC++, MFC, .NET and C++/CLI. Oh, and you might want to check out his blog on C++/CLI, MFC, .NET and a lot of other stuff - blog.voidnish.com.
 
Nish loves reading Science Fiction, P G Wodehouse and Agatha Christie, and also fancies himself to be a decent writer of sorts. He has authored a romantic comedy Summer Love and Some more Cricket as well as a programming book – Extending MFC applications with the .NET Framework.
 
Nish's latest book C++/CLI in Action published by Manning Publications is now available for purchase. You can read more about the book on his blog.
 
Despite his wife's attempts to get him into cooking, his best effort so far has been a badly done omelette. Some day, he hopes to be a good cook, and to cook a tasty dinner for his wife.

Comments and Discussions

 
GeneralMy vote of 5 PinmemberMisopetha9-Jun-13 22:40 
Questionblocking with this Pinmembernjupas2-Nov-06 5:13 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web03 | 2.8.1411028.1 | Last Updated 1 Nov 2001
Article Copyright 2001 by Nish Sivakumar
Everything else Copyright © CodeProject, 1999-2014
Layout: fixed | fluid