Sync By Monitor : Monitor « Thread « Visual C++ .NET

Home
Visual C++ .NET
1.2D
2.Class
3.Collections
4.Data Type
5.Database ADO.net
6.Delegate
7.Development
8.File Directory
9.Function
10.Generics
11.GUI Form
12.Language Basics
13.Network
14.Reflection
15.Security
16.Statement
17.Structure
18.Thread
19.XML
C / ANSI-C
C Tutorial
C++
C++ Tutorial
Visual C++ .NET » Thread » Monitor 
Sync By Monitor
 
#include "stdafx.h"
using namespace System;
using namespace System::Threading;

ref class MyThread
{
    static Object^ MonitorObject = gcnew Object();

public:
    void FOne();
    void FTwo();
    void FThree();
};


void MyThread::FOne()
{
    Monitor::Enter(MonitorObject);
    for (Int32 i = 0; i < 3; i++)
    {
        Console::WriteLine("FOne   Waits  {0}", i.ToString());
        Monitor::Wait(MonitorObject);
        Console::WriteLine("FOne   Pulses {0}", i.ToString());
        Monitor::Pulse(MonitorObject);
        Thread::Sleep(1);
    }
    Monitor::Exit(MonitorObject);
    Console::WriteLine("FOne   exits monitor");
}

void MyThread::FTwo()
{
    Monitor::Enter(MonitorObject);
    for (Int32 i = 0; i < 3; i++)
    {
        Console::WriteLine("FTwo   Pulses {0}", i.ToString());
        Monitor::Pulse(MonitorObject);
        Thread::Sleep(1);
        Console::WriteLine("FTwo   Waits  {0}", i.ToString());
        Monitor::Wait(MonitorObject);
    }
    Monitor::Exit(MonitorObject);
    Console::WriteLine("FTwo   exits monitor");
}

void MyThread::FThree()
{
    if (!Monitor::TryEnter(MonitorObject))
    {
        Console::WriteLine("FThree was not able to lock");
        return;
    }
    Console::WriteLine("FThree got a lock");

    Monitor::Exit(MonitorObject);
    Console::WriteLine("FThree exits monitor");
}


void main()
{
    MyThread ^myThr1 = gcnew MyThread();

    (gcnew Thread(gcnew ThreadStart(myThr1, &MyThread::FOne)))->Start();
    Thread::Sleep(2);


    (gcnew Thread(gcnew ThreadStart(myThr1, &MyThread::FTwo)))->Start();
    Thread::Sleep(2);

    for (int i = 0; i < 2; i++)
    {
        (gcnew Thread(
            gcnew ThreadStart(myThr1, &MyThread::FThree)))->Start();
        Thread::Sleep(50);
   }
}

   
  
Related examples in the same category
www.java2java.com | Contact Us
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.