欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

C#【多线程-线程同步】-SemaphoreSlim业务应用场景

程序员文章站 2022-07-12 11:19:42
...
SemaphoreSlim业务应用场景
一.首先说一下SemaphoreSlim
   1.什么是SemaphoreSlim?
   官网上面解释: 对可同时访问资源或资源池的线程数加以限制的 Semaphore 的轻量替代。
  个人理解:对同一个资源,多个线程同时并发访问,起到对线程数控制的作用。
 
二.业务场景进行理解
  比如,售票窗口,需要开两个窗口售票,买票人员只能在这两个窗口买票
 
 三.建一个控制台
 
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace _05SemaphoreSlim
{
    class Program
    {
//定义两个信号量(两个窗口)
       private static SemaphoreSlim semaphore = new SemaphoreSlim (2);
       // A padding interval to make the output more orderly.
       private static int padding;

       static void AccessDatabase(string name ,int seconds)
       {
          semaphore.Wait();
          Console.WriteLine("wait to access base{0}",
                                name);
          
          Console.WriteLine("wait ganted to access base{0}",
                               name);
          Thread.Sleep(seconds);
          Console.WriteLine("completed ganted to access base{0}",
                               name);
          semaphore.Release();
       }
       public static void Main()
       {
          for (int i=1;i<70;i++)
          {
              string name = "Thread"+i;
              int s = 2 + 2 * i;
              var t = new Thread(()=> AccessDatabase(name, s));
             t.Start();

          }

       }
    }
}

 

Wait: 假如当前信号量不到2个,wait方法将不进行阻塞暂停,如果信号量未2个,当前线程执行到wait方法进行暂停,等待其它线程释放 信号量+1
Release:释放线程,信号量-1