Locking a thread function using Monitor::Enter Monitor::Exit

I have a thread class with two functions:

using namespace System::Threading;
public ref class SecThr
{
public:
 int j;

void wralot()
{
    for (int i=0; i<=400000;i++)
    {
    j=i;
    if ((i%10000)==0) 
        Console::WriteLine(j);
    }
}

void setalot()
{
    Monitor::Enter(this);
    for (int i=0; i<=400000;i++)
    {
    j=7;
    }
    Monitor::Exit(this);

}
 };


int main(array<System::String ^> ^args)
{
Console::WriteLine("Hello!");

SecThr^ thrcl=gcnew SecThr;
Thread^ o1=gcnew Thread(gcnew ThreadStart(thrcl, &SecThr::wralot));
Thread^ o2=gcnew Thread(gcnew ThreadStart(thrcl, &SecThr::setalot));
o2->Start();
o1->Start();
o1->Join();
o2->Join();

So, for locking "setalot" function i've used MOnitor::Enter-Exit block. But the output is like i'm running only one thread with function "wralot"

0 10000 20000 30000 40000 7 //here's "setalot" func 60000 e t.c.

Why all the output data is not changed to const (7) by "setalot" func

Jon Skeet
people
quotationmark

I think you've misunderstood what Monitor::Enter does. It's only a cooperative lock - and as wralot doesn't try to obtain the lock at all, the actions of setalot don't affect it. It's not really clear why you expected to get a constant output of 7 due to setalot - if wralot did try to obtain the lock, it would just mean that one of them would "win" and the other would have to wait. If wralot had to wait, there'd be no output while setalot was running, and then wralot would go do its thing - including setting j to i on every iteration.

So basically, both threads are starting, and setalot very quickly sets j to 7 a lot of times... that's likely to complete in the twinkling of an eye in computer terms, compared with a Console.WriteLine call. I suggest you add a call to Console::WriteLine at the end of setalot so you can see when it's finished. Obviously after that, it's completely irrelevant - which is why you're seeing 60000, 70000 etc.

people

See more on this question at Stackoverflow