如果在线程之间共享数据,则可能会出现线程争用的问题
1,局一个线程争用的例子:
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Threading; namespace ConsoleApplication6 { class Program { static void Main(string[] args) { SampleTask st = new SampleTask(); StateObject so = new StateObject(); //开启20个任务,每个任务循环执行StateObject类的ChangeState方法 for (int i = 0; i < 20; i++) { new Task(st.RaceCondition, so).Start(); } Console.WriteLine("运行完成"); Console.ReadLine(); } } //简单的任务类 class SampleTask { public void RaceCondition(object o) { Trace.Assert(o is StateObject, "只能传递StateObject对象"); StateObject s = o as StateObject; int i = 0; //单个任务循环执行StateObject类的ChangeState方法 while (true) { s.ChangeState(++i); } } } //状态类 //如果state为5,则加1,后面跟着检查state,如果不为6,就出现了争用。 class StateObject { int state = 5; public void ChangeState(int loop) { if (state == 5) { state++; //为false说明出现争用,则程序断言(弹出框) Trace.Assert(state == 6, "在循环了" + loop.ToString() + "次后出现了争用"); } state = 5; } } }
2,解决办法:
①:使用lock锁定共享的s变量
//简单的任务类 class SampleTask { public void RaceCondition(object o) { Trace.Assert(o is StateObject, "只能传递StateObject对象"); StateObject s = o as StateObject; int i = 0; //单个任务循环执行StateObject类的ChangeState方法 while (true) { //使用lock锁定共享的s变量 lock (s) { s.ChangeState(++i); } } } }
②:将共享对象设置为线程安全的对象
//状态类 //如果state为5,则加1,后面跟着检查state,如果不为6,就出现了争用。 class StateObject { int state = 5; public void ChangeState(int loop) { //将共享对象设置为线程安全的对象 lock (this) { if (state == 5) { state++; //为false说明出现争用,则程序断言(弹出框) Trace.Assert(state == 6, "在循环了" + loop.ToString() + "次后出现了争用"); } state = 5; } } }
本文出自 “程序猿的家--Hunter” 博客,请务必保留此出处http://962410314.blog.51cto.com/7563109/1609395
原文地址:http://962410314.blog.51cto.com/7563109/1609395