多线程操作集合时如何保证集合的线程安全性

先看示例代码1

[csharp]  view plain  copy
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Threading;  
  4.    
  5. namespace CollSecExp  
  6. {  
  7.     class Program  
  8.     {          
  9.         static void Main(string[] args)  
  10.         {  
  11.             List<int> list = new List<int>();  
  12.             for (int i = 0; i < 10; i++)  
  13.             {  
  14.                 list.Add(i);  
  15.             }  
  16.   
  17.             Thread t1 = new Thread(() =>  
  18.             {  
  19.                  foreach (var item in list)  
  20.                  {  
  21.                      Console.WriteLine("t1.item:{0}", item);  
  22.                      Thread.Sleep(1000);  
  23.                  }  
  24.             });  
  25.             t1.Start();  
  26.   
  27.             Thread t2 = new Thread(() =>  
  28.             {  
  29.                 Thread.Sleep(1000);  
  30.                 list.RemoveAt(1);  
  31.                 list.RemoveAt(3);  
  32.                 foreach (var item in list)  
  33.                 {  
  34.                      Console.WriteLine("t2.item:{0}", item);  
  35.                  }  
  36.             });  
  37.             t2.Start();  
  38.         }  
  39.     }  
  40. }  

运行示例代码1,会抛出InvalidOperationException异常,提示“集合已修改;可能无法执行枚举操作。”

这是因为,线程2移除index=13的元素导致集合被修改,很显然,此时线程1遍历集合肯定会出错,因为它这时遍历得到的结果与实际情况已经不符,就算取出也没有了价值。

 

针对这种情况,我们可以对集合加锁来保证线程对集合操作的同步。

奋斗修改示例代码1,得到示例代码2

[csharp]  view plain  copy
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Threading;  
  4.    
  5. namespace CollSecExp  
  6. {  
  7.     class Program  
  8.     {          
  9.         static void Main(string[] args)  
  10.         {  
  11.             object sycObj = new object();  
  12.             List<int> list = new List<int>();  
  13.             for (int i = 0; i < 10; i++)  
  14.             {  
  15.                 list.Add(i);  
  16.             }  
  17.    
  18.             Thread t1 = new Thread(() =>  
  19.             {  
  20.                 lock (sycObj)  
  21.                 {  
  22.                     foreach (var item in list)  
  23.                     {  
  24.                         Console.WriteLine("t1.item:{0}", item);  
  25.                         Thread.Sleep(1000);  
  26.                     }  
  27.                 }  
  28.             });  
  29.             t1.Start();  
  30.   
  31.             Thread t2 = new Thread(() =>  
  32.             {  
  33.                 Thread.Sleep(1000);  
  34.                 lock (sycObj)  
  35.                 {  
  36.                     list.RemoveAt(1);  
  37.                     list.RemoveAt(3);  
  38.                     foreach (var item in list)  
  39.                     {  
  40.                         Console.WriteLine("t2.item:{0}", item);  
  41.                     }  
  42.                }  
  43.             });  
  44.             t2.Start();  
  45.         }  
  46.     }  
  47. }  

示例代码2与示例代码1的区别仅在加锁操作上,变化的地方已经用红色字体标出。

再次运行代码,未报错,得到以下运行结果:

 

从结果我们可以看出,加锁以后,线程1执行的结果是正常的,正确的输出了list10个元素。同样,线程2执行结果也是正常的,移除index=13的元素后,遍历出剩下的8个元素。不过这里要补充说明一下,移除index=1的元素时,为什么是源集合中的index=14的元素被移除?那是因为移除index=1的元素后,index=4的元素在新集合中的index就变成3了,所以会有这样的结果。

 

另外,在编写测试代码时,还遇到了下面这样一个问题,拿出来分享一下。

大哭将线程2的代码改写成下面的形式。

[csharp]  view plain  copy
  1. Thread t2 = new Thread(() =>  
  2. {  
  3.      Thread.Sleep(1000);  
  4.      lock (sycObj)  
  5.      {  
  6.           foreach(var item in list)  
  7.           {  
  8.                if (item % 2 == 0)  
  9.                {  
  10.                     list.Remove(item);  
  11.                }  
  12.           }  
  13.           foreach (var item in list)  
  14.           {  
  15.                Console.WriteLine("t2.item:{0}", item);  
  16.           }  
  17.      }  
  18. });  
  19. t2.Start();  

运行程序,你会发现,线程1能正常运行,但是在执行线程2时,同样会InvalidOperationException异常,提示信息仍为“集合已修改;可能无法执行枚举操作。”

分析代码,发现是在遍历集合并作移除操作的代码部分(已用青色字体标出),对于这点其实不在多线程程序中也是会出错的。很明显这种做法就不对,你既想遍历集合又想动态删除某些符合条件的元素,这是不可能的,哪有这么好的事。

 

其实,除了加锁,还可以使用System.Collections.Concurrent命名空间中提供的ConcurrentBag<T>来代替List<T>,ConcurrentBag<T>是线程安全的集合类。

奋斗代码片段3:

[csharp]  view plain  copy
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Threading;  
  4. using System.Collections.Concurrent;   //注1   
  5.   
  6. namespace CollSecExp  
  7. {  
  8.     class Program  
  9.     {          
  10.         static void Main(string[] args)  
  11.         {  
  12.             ConcurrentBag<int> list = new ConcurrentBag<int>();  
  13.             for (int i = 0; i < 10; i++)  
  14.             {  
  15.                 list.Add(i); //注2  
  16.             }  
  17.    
  18.             Thread t1 = new Thread(() =>  
  19.             {  
  20.                 foreach (var item in list)  
  21.                 {  
  22.                     Console.WriteLine("t1.item:{0}", item);  
  23.                     Thread.Sleep(1000);  
  24.                 }  
  25.             });  
  26.             t1.Start();  
  27.   
  28.             Thread t2 = new Thread(() =>  
  29.             {  
  30.                 Thread.Sleep(1000);  
  31.                 int a;  
  32.                 list.TryTake(out a); //注3  
  33.                 foreach (var item in list)  
  34.                 {  
  35.                     Console.WriteLine("t2.item:{0}", item);  
  36.                 }  
  37.             });  
  38.             t2.Start();  
  39.         }  
  40.     }  
  41. }  

示例代码3与示例代码1的区别在于使用ConcurrentBag<int>来代替List<int>保存集合数据。这样一来就算不加锁,也能保证线程操作的同步。

有几点稍微补充说明一下:

[注1]需要引用命名空间System.Collections.Concurrent才可以使用ConcurrentBag<T>类。

[注2]ConcurrentBag<T>的Add方法与List<T>的Add方法相同。

[注3]ConcurrentBag<T>的移除方法为TryTakeList<T>的移除方法不相同,这点需要注意。

 运行程序,得到结果:

 

会发现线程1与线程2能正常运行,只是此时线程12会并行执行,且遍历集合时会从项值大的到小的顺序进行,关于这点,以后再研究。

 

就到这里了。再见

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值