C#学习之多线程开发技术(六)

我就是我 2022-08-09 02:23 99阅读 0赞

线程同步之LOCK锁

在Framework中已经为我们提供了三个加锁的机制,分别是
Monitor类
Lock关键字
Mutex类

都是锁定数据或是锁定被调用的函数。
Mutex则多用于锁定多线程间的同步调用。简单的说,Monitor和Lock多用于锁定被调用端,而Mutex则多用锁定调用端。
Monitor和Lock将代码段标记为临界区,其实现原理是首先锁定某一私有对象,然后执行代码段中的语句,当代码段中的语句执行完毕后,再解除锁。

————————-LOCK结构

  1. private Object obj = new Object();//定义一私有对象
  2. //……其它代码
  3. lock(this)
  4. {
  5. //……操作临界资源
  6. }

例如:

  1. lock(this)
  2. {
  3. Console.WriteLine("{0}{1}", str, System.DateTime.Now.Millisecond.ToString());
  4. Thread.Sleep(50);
  5. }

-———————-lock举例(控制台程序)

下面程序中有两个线程thread1、thread2和一个TestFunc函数,TestFunc会打印出调用它的线程名和调用的时间(mm级的),两个线程分别以30mm和100mm来调用TestFunc这个函数。TestFunc执行的时间为50mm。

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading;
  6. using System.Threading.Tasks;
  7. namespace 线程同步
  8. {
  9. class Program
  10. {
  11. #region 变量区
  12. Thread thread1 = null;
  13. Thread thread2 = null;
  14. Mutex metux = null;
  15. #endregion
  16. static void Main(string[] args)
  17. {
  18. Program p = new Program();
  19. p.RunThread();
  20. Thread.Sleep(10000);
  21. p.CloseThread();
  22. }
  23. ///---
  24. public Program()
  25. {
  26. metux = new Mutex();
  27. thread1 = new Thread(thread1Func);
  28. thread2 = new Thread(thread2Func);
  29. }
  30. /// <summary>
  31. /// ---启动线程
  32. /// </summary>
  33. public void RunThread()
  34. {
  35. thread1.Start();
  36. thread2.Start();
  37. }
  38. /// <summary>
  39. /// ---线程1
  40. /// </summary>
  41. private void thread1Func()
  42. {
  43. for (int i = 0; i < 10; i++)
  44. {
  45. TestFunc("thread1 had run " + i.ToString() + "times ");
  46. Thread.Sleep(30);
  47. }
  48. }
  49. /// <summary>
  50. /// ---线程2
  51. /// </summary>
  52. private void thread2Func()
  53. {
  54. for (int i = 0; i < 10; i++)
  55. {
  56. TestFunc("thread2 had run " + i.ToString() + "times ");
  57. Thread.Sleep(100);
  58. }
  59. }
  60. /// <summary>
  61. /// ---调用函数
  62. /// </summary>
  63. /// <param name="str"></param>
  64. private void TestFunc(string str)
  65. {
  66. lock(this)
  67. {
  68. Console.WriteLine("{0}{1}", str, System.DateTime.Now.Millisecond.ToString());
  69. Thread.Sleep(50);
  70. }
  71. }
  72. /// <summary>
  73. /// ---杀死线程
  74. /// </summary>
  75. private void CloseThread()
  76. {
  77. if (thread1.IsAlive)
  78. {
  79. thread1.Abort();
  80. }
  81. if (thread2.IsAlive)
  82. {
  83. thread2.Abort();
  84. }
  85. }
  86. }
  87. }

输出结果(不同计算机上,结果可能不同):

Center

发表评论

表情:
评论列表 (有 0 条评论,99人围观)

还没有评论,来说两句吧...

相关阅读