首页 > 编程开发 > Objective-C编程 >
-
c#线程基础之原子操作
使用System.Threading.Interlocked类可以提高线程的安全性,具体资料参考msdn: http://msdn.microsoft.com/zh-cn/library/system.threading.interlocked.aspx 一般情况下,在子线程内使用i++这样的方式访问全局变量的方式是不安全的做法。测试下面的代码,在test1中经过100次number++,number并没有每次从0变为100,而test2则没有问题。
usingSystem;
usingSystem.Windows.Forms;
namespaceWindowsApplication32
{
publicpartialclassForm1:Form
{
publicForm1()
{
InitializeComponent();
}
intnumber=0;
///<summary>
///普通的变量访问方式
///</summary>
privatevoidtest1()
{
for(intm=0;m<10;m++)
{
number++;
System.Threading.Thread.Sleep(100);
}
Console.WriteLine(number);
}
privatevoidbutton1_Click(objectsender,EventArgse)
{
number=0;
for(inti=0;i<10;i++)
{
newSystem.Threading.Thread(test1).Start();
}
}
///<summary>
///使用原子的访问方式
///</summary>
privatevoidtest2()
{
for(intm=0;m<10;m++)
{
System.Threading.Interlocked.Increment(refnumber);
System.Threading.Thread.Sleep(100);
}
Console.WriteLine(number);
}
privatevoidbutton2_Click(objectsender,EventArgse)
{
number=0;
for(inti=0;i<10;i++)
{
newSystem.Threading.Thread(test2).Start();
}
}
}
}