.net中的System.Threading.Interlocked类可以为多个线程共享的变量提供原子操作
来源:互联网 发布:php notice 关闭 编辑:程序博客网 时间:2024/05/16 04:12
.net中的System.Threading命名空间的Interlocked类可以为多个线程共享的变量提供原子操作。
经验显示,那些需要在多线程下被保护的资源通常是整型的,而这些被共享的整型值最常见的操作就是增加、减少。Interlocked类提供了一个专门的机制用于完成这些特定的操作。
下面的例子是一个没有使用Interlocked类的操作:
class Program
{
static long counter = 1;
static void Main(string[] args)
{
System.Threading.Thread t1 = new System.Threading.Thread(f1);
System.Threading.Thread t2 = new System.Threading.Thread(f2);
t1.Start();
t2.Start();
t1.Join();
t2.Join();
System.Console.Read();
}
static void f1)
{
for (int i = 1; i <= 1000; i++)
{
counter++;
System.Console.WriteLine("Counter++ {0}", counter);
System.Threading.Thread.Sleep(10);
}
}
static void f2)
{
for (int i = 1; i <= 1000; i++)
{
counter--;
System.Console.WriteLine("Counter++ {0}", counter);
System.Threading.Thread.Sleep(10);
}
}
}
最后的结果counter的值为2,如果我们是用单线程操作的话counter的值应该是1,下面的例子是使用Interlocked类的:
class Program
{
static long counter = 1;
static void Main(string[] args)
{
System.Threading.Thread t1 = new System.Threading.Thread(f1);
System.Threading.Thread t2 = new System.Threading.Thread(f2);
t1.Start();
t2.Start();
t1.Join();
t2.Join();
System.Console.Read();
}
static void f1()
{
for (int i = 1; i <= 5; i++)
{
Interlocked.Increment(ref counter);
System.Console.WriteLine("Counter++ {0}", counter);
System.Threading.Thread.Sleep(10);
}
}
static void f2()
{
for (int i = 1; i <= 5; i++)
{
Interlocked.Decrement(ref counter);
System.Console.WriteLine("Counter++ {0}", counter);
System.Threading.Thread.Sleep(10);
}
}
}
这次最后的结果是1。
在大多数计算机上,增加变量操作不是一个原子操作,需要执行下列步骤:
1、将实例变量中的值加载到寄存器中。
2、增加或减少该值。
3、在实例变量中存储该值。(来自MSDN)
- .net中的System.Threading.Interlocked类可以为多个线程共享的变量提供原子操作
- 【进程线程与同步】5.4 System.Threading.Interlocked 为多个线程共享的变量提供原子操作
- C#中为多线程变量提供原子操作的类Interlocked
- C#中的原子操作Interlocked,你真的了解吗?
- C#中的原子操作Interlocked你真的了解吗?
- 多个线程共享DLL中的变量
- C# 多线程Interlocked类保证原子操作
- 原子操作Interlocked
- atomic提供原子操作的类
- 线程4:原子变量与原子操作
- 用户模式的线程同步原子访问:InterLocked互锁函数
- 原子操作 Interlocked系列函数
- 原子操作 Interlocked系列函数
- 原子操作 Interlocked系列函数
- 关于c#中数据的原子操作及让人郁闷的InterLocked类
- System.Math.Min(System.Threading.Interlocked.Increment(i), i - 1)的问题
- Windows Via C/C++:用户模式下的线程同步——原子操作:Interlocked函数族
- Windows Via C/C++:用户模式下的线程同步——原子操作:Interlocked函数族
- v$session_longops 查看进程的进度
- Touch事件分发机制
- 马里奥设计总监揭秘创作过程
- ubuntu运行android studio出错unable to run mksdcard sdk tool
- ffmpeg 视频
- .net中的System.Threading.Interlocked类可以为多个线程共享的变量提供原子操作
- 代理模式
- 浅谈HTTP中Get与Post的区别
- Android Style.xml 详解
- Spanned.SPAN_EXCLUSIVE_EXCLUSIVE的含义
- 【软件设计模式】代理模式
- Spring3.0
- 我的第一个Struts2框架开发-Hello World
- 关于MFC客户端窗口全屏和撤销全屏问题