首页 > 编程语言 > 详细

C#之:线程同步 Semaphore类和 SemaphoreSlim类

时间:2020-04-24 18:07:08      阅读:49      评论:0      收藏:0      [点我收藏+]

记一次SemaphoreSlim的使用

 1 using System;
 2 using System.Threading;
 3 
 4 namespace ConsoleApp1
 5 {
 6     public class Program2
 7     {
 8         #region Field(字段)
 9 
10         private static SemaphoreSlim _semaphore = new SemaphoreSlim(4);
11 
12         #endregion Field(字段)
13 
14         #region Public Method(公开方法)
15 
16         private static void acquireSemaphore(string name, int seconds)
17         {
18             Console.WriteLine("{0} wait " + DateTime.Now, name);
19             _semaphore.Wait();
20             Console.WriteLine("{0} access " + DateTime.Now, name);
21             Thread.Sleep(TimeSpan.FromSeconds(seconds));
22             Console.WriteLine("{0} Release " + DateTime.Now, name);
23             _semaphore.Release();
24         }
25 
26         private static void Main(string[] args)
27         {
28             for (int i = 1; i <= 6; i++)
29             {
30                 string threadName = "thread" + i;
31                 int secondsToWait = 2 + 2 * i;
32                 var t = new Thread(() => acquireSemaphore(threadName, secondsToWait));
33                 t.Start();
34             }
35             Console.ReadKey();
36         }
37 
38         #endregion Public Method(公开方法)
39     }
40 }

执行结果如下:
技术分享图片

解释下:

SemaphoreSlim(4)限定最大入口并发数4,前面‘thread1’,‘thread2’,‘thread3’,‘thread5’四个线程先到,‘thread4’、‘thread6’后到进行等待,4秒后thread1释放,‘thread6‘进入,6秒后thread2释放,thread4进入。

C#之:线程同步 Semaphore类和 SemaphoreSlim类

原文:https://www.cnblogs.com/Nine4Cool/p/12768981.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!