lock demo : Lock « 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 » Lock 
lock demo
 

#include "stdafx.h"

#include <msclr/lock.h>

using namespace System;
using namespace System::Collections;
using namespace System::Threading;
using namespace msclr;

ref class App
{
private:
    ArrayList^ myArray;

public:
    App() { myArray = gcnew ArrayList()}

    void Thread1()
    {
        while (true)
        {
            try
            {
                lock l1 (myArray->SyncRoot, 500);
                Console::WriteLine("In Thread 1 Lock");
                Thread::Sleep(1000);
            }
            catch(...
            {
                Console::WriteLine("Failed to get sync in Thread 1");
            }
        }
    }

    void Thread2()
    {
        lock l2(myArray->SyncRoot, lock_later);
        while (true)
        {
            if (l2.try_acquire(500))
            {
                Console::WriteLine("In Thread 2 lock");
                Thread::Sleep(1000);
                l2.release();
            }
            else
            {
                Console::WriteLine("Failed to get sync in Thread 2");
            }
        }
    }
};

int main(array<System::String ^> ^args)
{
    App^ app = gcnew App();

    Thread ^th1 = gcnew Thread(gcnew ThreadStart(app, &App::Thread1));
    Thread ^th2 = gcnew Thread(gcnew ThreadStart(app, &App::Thread2));

    th1->IsBackground = true;
    th2->IsBackground = true;

    th1->Start();
    th2->Start();

    Console::ReadLine();
    return 0;
}

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