Mutex是可以进程间同步的同步基元。

  名称 说明
Mutex()

Mutex 类的新实例。

Mutex(Boolean)

Mutex 类的新实例。

Mutex(Boolean, String)

Mutex 类的新实例。

Mutex(Boolean, String, Boolean)

Mutex 类的新实例。

Mutex(Boolean, String, Boolean, MutexSecurity)

Mutex 类的新实例。

 

 1 private static Mutex _asyncLocker = new Mutex();
 2 static void Main(string[] args)
 3 {
 4     MutextDemo mutext = new MutextDemo();
 5     int test = 0;
 6     Thread th1 = new Thread(() =>
 7     {
 8         for (int i = 0; i < 100; i++)
 9             Add(ref test);
10     });
11     th1.Name = "T1";
12     Thread th2 = new Thread(() =>
13     {
14         for (int i = 0; i < 100; i++)
15             Add(ref test, 10);
16     });
17     th2.Name = "T2";
18     Thread th3 = new Thread(() =>
19     {
20         for (int i = 0; i < 100; i++)
21             Add(ref test, 20);
22     });
23     th3.Name = "T3";
24     Thread th4 = new Thread(() =>
25     {
26         for (int i = 0; i < 100; i++)
27             Add(ref test, 30);
28     });
29     th4.Name = "T4";
30     Thread th5 = new Thread(() =>
31     {
32         for (int i = 0; i < 100; i++)
33             Add(ref test, 40);
34     });
35     th5.Name = "T5";
36 
37     th1.Start();
38     th2.Start();
39     th3.Start();
40     th4.Start();
41     th5.Start();
42 
43     Console.ReadKey();
44 }
45 
46 public static void Add(ref int value, int sleep = 0)
47 {
48     _asyncLocker.WaitOne();
49     int temp = value;
50     Thread.Sleep(sleep);
51     value = temp + 1;
52     Console.WriteLine($"{Thread.CurrentThread.Name} : {value}");
53     _asyncLocker.ReleaseMutex();
54 }
Mutex示例代码

相关文章:

  • 2021-07-10
  • 2022-01-06
  • 2021-09-28
  • 2021-12-09
  • 2022-12-23
  • 2022-12-23
  • 2022-01-08
猜你喜欢
  • 2019-07-18
  • 2021-09-15
  • 2022-12-23
  • 2022-12-23
  • 2021-11-11
  • 2021-09-19
相关资源
相似解决方案