using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
namespace ShareVar
{
class SerialNum
{
private static int _num = 0;
private object lockKey = new object();
public SerialNum()
{
//_num = 0;
}
public int Num
{
get
{
//thread safe mode by lock
lock (lockKey)
{
_num++;
int myNum = _num;
//System.Threading.Thread.Sleep(100);
return myNum;
}
//thread safe by readwritelock
//int myNum;
//ReaderWriterLock rwl = new ReaderWriterLock();
////read
//rwl.AcquireReaderLock(Timeout.Infinite);
//myNum = _num + 1;
//rwl.ReleaseReaderLock();
//rwl.AcquireWriterLock(Timeout.Infinite);
//_num = myNum;
//rwl.ReleaseWriterLock();
//System.Threading.Thread.Sleep(100);
//return myNum;
//thread not safe
//_num++;
//int myNum = _num;
//System.Threading.Thread.Sleep(1000);
//return myNum;
}
}
}
class Test
{
private SerialNum sn = new SerialNum();
static void Main(string[] args)
{
Thread[] threadArray = new Thread[20];
int threadNum;
Test test = new ShareVar.Test();
ThreadStart myThreadStart = new ThreadStart(test.SendMsg);
for (threadNum = 0; threadNum < 20; threadNum++)
{
threadArray[threadNum] = new Thread(myThreadStart);
}
//thread start
for (threadNum = 0; threadNum < 20; threadNum++)
{
threadArray[threadNum].Start();
}
////Wait until all the thread spawn out finish.
for (threadNum = 0; threadNum < 20; threadNum++)
{
threadArray[threadNum].Join();
}
Console.ReadLine();
}
public void SendMsg()
{
int myNum = sn.Num;
Console.WriteLine(myNum);
}
}
}