using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
namespace Thread_SpinLock
{
class ShearedResource //多线程共享的资源
{
public int instanceCount = 0; //!实例字段
public static int counter = 0; //!静态字段
}
class Program
{
private static SpinLock _spinLock = new SpinLock();
private static void IncreaseCount(Object obj)
{
bool lockTaken = false;
try
{
_spinLock.Enter(ref lockTaken);
int beginNum = (obj as ShearedResource).instanceCount;
for (int i = 0; i < 100000; i++)
beginNum++;
(obj as ShearedResource).instanceCount = beginNum;
Console.WriteLine("Thread ID:{0}, Count: {1}", Thread.CurrentThread.ManagedThreadId, beginNum);
}
finally
{
if (lockTaken)
_spinLock.Exit();
}
}
static void Main(string[] args)
{
const int threadCount = 15;
ShearedResource sr = new ShearedResource();
Thread[] threads = new Thread[threadCount];
for (int i = 0; i < threadCount; i++)
{
threads[i] = new Thread(new ParameterizedThreadStart(IncreaseCount)); //!线程带参
threads[i].Start(sr);
}
Console.ReadKey();
}
}
}