• C#中的信号量---Semaphore


    emaphore是System.Threading下的类,限制可同时访问某一资源或资源池的线程数。

    常用构造方法

    https://msdn.microsoft.com/zh-cn/library/e1hct27h(v=vs.110).aspx

    public Semaphore(
    	int initialCount,
    	int maximumCount
    )
    

    参数

    initialCount
    Type: System.Int32

    可以同时授予的信号量的初始请求数。

    maximumCount
    Type: System.Int32

    可以同时授予的信号量的最大请求数。

     示例代码

    复制代码
    class Program
        {
           static Semaphore sema = new Semaphore(1,1);
          
            static void Main(string[] args)
            {
                for (int i = 0; i < 3; i++)
                {
                    var thread = new Thread(Test) { Name = $"Thread{ i }" };
                    thread.Start();
                }
                Console.ReadKey();
            }
    
    
            static void Test()
            {
                sema.WaitOne();
                for (int i = 0; i < 3; i++)
                {
                    Console.WriteLine($"ThreadName:{ Thread.CurrentThread.Name} i:{i}");
                    Thread.Sleep(1000);
                }
                sema.Release();
                Console.ReadKey();
            }
        }
    复制代码

    代码说明:

    static Semaphore sema = new Semaphore(1,1);

    声明一个信号量,指示控制的资源初始和最大线程并发数为1

    sema.WaitOne();
    for (int i = 0; i < 3; i++)
    {
    Console.WriteLine($"ThreadName:{ Thread.CurrentThread.Name} i:{i}");
    Thread.Sleep(1000);
    }
    sema.Release();

    使用以上两个方法控制资源,某个线程执行sema.WaitOne()方法时,若有其他线程已经占用资源,此方法将阻塞,直到,其他线程释放,即调用sema.Release();方法

    执行效果如下:

    同一段时间内,只有一个线程进入共享资源中。

    以下是最大并发数为2的执行效果:

    static Semaphore sema = new Semaphore(2,2);

    同一段时间内,有两个线程进入了贡献资源中

  • 相关阅读:
    Preparing for Merge Sort(二分)
    Polycarp's phone book(unordered_mpa 大法好)
    Yet Another Task with Queens
    nginx 初时
    JSON.stringfiy 序列化
    css grid布局使用
    遍历对象属性5种方法,排列顺序规则
    归并方法
    处理地图经纬度,保留6位小数
    js 操作方法
  • 原文地址:https://www.cnblogs.com/bruce1992/p/14220464.html
Copyright © 2020-2023  润新知