对于多线程临界点的几种处理方式
1: lock
2:Interlocked.Increment(ref page) ++ ,Interlocked.Decrement(ref page)--
如下代码,我们执行Page3的时候page输出会等于100或者比100小
解决方法,用Page或者Page1方法
public class Program
{
static void Main(string[] args)
{
for (int num=0;num++<10;) {
Test test = new Test();
List<Thread> list = new List<Thread>();
for (int a = 0; a < 100; a++)
{
//var thread = new Thread(test.Page3);
var thread = new Thread(test.Page1);
list.Add(thread);
}
list.ForEach(x => x.Start());
list.ForEach(x => x.Join());
Console.WriteLine(test.page);
Console.WriteLine("______________");
}
Console.ReadKey();
}
}
public class Test
{
public ThreadLocal<int> ThreadLocal = new ThreadLocal<int>();
public int page = 0;
public void Page(Object obj)
{
lock (obj) {
this.page++;
}
}
public void Page1()
{
Interlocked.Increment(ref page);
}
public void Page3()
{
this.page++;
}
}