利用原子操作加锁确保线程安全——Interlocked

作者:追风剑情 发布于:2017-9-19 17:39 分类:C#

这是官方例子 https://msdn.microsoft.com/zh-cn/library/system.threading.interlocked.aspx


  1. using System;
  2. using System.Threading;
  3.  
  4. namespace InterlockedExchange_Example
  5. {
  6. class MyInterlockedExchangeExampleClass
  7. {
  8. //0 for false, 1 for true.
  9. private static int usingResource = 0;
  10.  
  11. private const int numThreadIterations = 5;
  12. private const int numThreads = 10;
  13.  
  14. static void Main()
  15. {
  16. Thread myThread;
  17. Random rnd = new Random();
  18.  
  19. for (int i = 0; i < numThreads; i++)
  20. {
  21. myThread = new Thread(new ThreadStart(MyThreadProc));
  22. myThread.Name = String.Format("Thread{0}", i + 1);
  23.  
  24. //等待一会再启动线程
  25. Thread.Sleep(rnd.Next(0, 1000));
  26. myThread.Start();
  27. }
  28.  
  29. Console.ReadKey();
  30. }
  31.  
  32. private static void MyThreadProc()
  33. {
  34. for (int i = 0; i < numThreadIterations; i++)
  35. {
  36. UseResource();
  37. //Wait 1 second before next attempt.
  38. Thread.Sleep(1000);
  39. }
  40. }
  41.  
  42. //A simple method that denies reentrancy.
  43. static bool UseResource()
  44. {
  45. //第1个访问Exchange()的线程会返回0,之后usingResource被设成1
  46. //这里利用原子操作加锁,确保if里的代码不会被多个线程同时访问
  47. //优点: 原子操作基于CPU,非阻塞,比lock效率高
  48. if (0 == Interlocked.Exchange(ref usingResource, 1))
  49. {
  50. Console.WriteLine("{0} acquired the lock", Thread.CurrentThread.Name);
  51.  
  52. //这里的代码是线程安全的
  53. //模拟处理一些工作
  54. Thread.Sleep(500);
  55.  
  56. Console.WriteLine("{0} exiting lock", Thread.CurrentThread.Name);
  57.  
  58. //usingResource被设成0(即,释放锁)
  59. Interlocked.Exchange(ref usingResource, 0);
  60. return true;
  61. }
  62. else
  63. {
  64. Console.WriteLine(" {0} was denied the lock", Thread.CurrentThread.Name);
  65. return false;
  66. }
  67. }
  68. }
  69. }


运行效果

111111.png

标签: C#

Powered by emlog  蜀ICP备18021003号-1   sitemap

川公网安备 51019002001593号