本文主要是介绍关于c#中数据的原子操作及让人郁闷的InterLocked类,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
首先,查书看了一下原子操作的概念,自己编了一程序试了一下,果然,在C#中除了int型的赋值支持原子操作,其他的应该都需要同步锁定。
测试代码如下:
using System.Collections.Generic;
using System.Text;
using System.Threading;
namespace Test2
... {
class Program2
...{
static void Main(string[] args)
...{
Thread thread1 = new Thread(new ThreadStart(ThreadFunction1));
Thread thread2 = new Thread(new ThreadStart(ThreadFunction2));
thread1.IsBackground = true;
thread2.IsBackground = true;
thread1.Start();
thread2.Start();
Console.ReadLine();
}
static long value = value1;
const long value1 = 0x1111111100000000;
const long value2 = 0x0000000011111111;
//static int value = 0;
//const int value1 = 0x11110000;
//const int value2 = 0x00001111;
static void ThreadFunction1()
...{
Console.WriteLine("Thread1 Start ...");
while(true)
...{
if (value == value1)
value = value2;
//Interlocked.Exchange(ref value, value2);
else
value = value1;
//Interlocked.Exchange(ref value, value1);
}
}
static void ThreadFunction2()
...{
Console.WriteLine("Thread2 Start ...");
//int bValue = 0;
long bValue = 0;
while (true)
...{
//bValue = Interlocked.Read(ref value);
bValue = value;
if (bValue != value1 && bValue != value2)
...{
Console.WriteLine("Error");
}
}
}
}
}
不过让人郁闷的是微软的System.Threading.InterLocked类,本来想用它替换Lock方法的,但测了一下其性能,发现对long型的操作竟然比lock还要慢,倒。。。
using System.Collections.Generic;
using System.Text;
namespace Test2
... {
class Program
...{
const long COUNT = 100000000;
static long count = COUNT;
static long var = 0;
static object obj = new object(); // lock锁
static void Main(string[] args)
...{
long start = 0;
start = System.DateTime.Now.Ticks;
while (count-- > 0)
...{
lock (obj)
...{
var++;
}
}
long duration = System.DateTime.Now.Ticks - start;
Console.WriteLine(duration);
start = System.DateTime.Now.Ticks;
var = 0;
count = COUNT;
while (count-- > 0)
...{
System.Threading.Interlocked.Increment(ref var);
}
duration = System.DateTime.Now.Ticks - start;
Console.WriteLine(duration);
}
}
}
下面是测试结果:
33437500
汗。。。不知道微软怎么处理的。因为在对int型的测试中,InterLocked比lock要快一个数量级呢。。。
这篇关于关于c#中数据的原子操作及让人郁闷的InterLocked类的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!