Sync By RWLock : 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 
Sync By RWLock
 

#include "stdafx.h"
using namespace System;
using namespace System::Threading;

ref class MyThread
{
    static ReaderWriterLock ^RWLock = gcnew ReaderWriterLock();
    static int iVal = 4;

public:
    static void ReaderThread();
    static void WriterThread();
};

void MyThread::ReaderThread()
{
    String ^thrName = Thread::CurrentThread->Name;
    while (true)
    {
        try
        {
            RWLock->AcquireReaderLock(2);
            Console::WriteLine("Reading in {0}. iVal is {1}",thrName, iVal);

            RWLock->ReleaseReaderLock();
            Thread::Sleep(4);
        }
        catch (ApplicationException^)
        {
            Console::WriteLine("Reading in {0}. Timed out", thrName);
        }
    }
}

void MyThread::WriterThread()
{
    while (iVal > 0)
    {
        RWLock->AcquireWriterLock(-1);

        Interlocked::Decrement(iVal);
        Console::WriteLine("Writing iVal to {0}", iVal);
        Thread::Sleep(7);

        RWLock->ReleaseWriterLock();
    }
}

void main()
{
    Thread ^thr1 = gcnew Thread(gcnew ThreadStart(&MyThread::ReaderThread));
    Thread ^thr2 = gcnew Thread(gcnew ThreadStart(&MyThread::ReaderThread));
    Thread ^thr3 = gcnew Thread(gcnew ThreadStart(&MyThread::WriterThread));

    thr1->Name = "Thread1";
    thr2->Name = "Thread2";

    thr1->IsBackground = true;
    thr2->IsBackground = true;

    thr1->Start();
    thr2->Start();
    thr3->Start();

    thr3->Join();
    Thread::Sleep(2);
}

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