Visual C++ .NET/Thread/Lock
Interlocked Vars
#include "stdafx.h"
using namespace System;
using namespace System::Threading;
ref class MyThread
{
static int iVal;
public:
static MyThread()
{
iVal = 5;
}
void ThreadFunc();
};
void MyThread::ThreadFunc()
{
while (Interlocked::Increment(iVal) < 15)
{
Thread ^thr = Thread::CurrentThread;
Console::WriteLine("{0} {1}", thr->Name, iVal);
Thread::Sleep(1);
}
}
void main()
{
MyThread ^myThr1 = gcnew MyThread();
Thread ^thr1 = gcnew Thread(gcnew ThreadStart(myThr1, &MyThread::ThreadFunc));
Thread ^thr2 = gcnew Thread(gcnew ThreadStart(myThr1, &MyThread::ThreadFunc));
thr1->Name = "Thread1";
thr2->Name = "Thread2";
thr1->Start();
thr2->Start();
}
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;
}
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);
}