Visual C++ .NET/Thread/Monitor

Материал из .Net Framework эксперт
Перейти к: навигация, поиск

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);
   }
}