zoukankan      html  css  js  c++  java
  • C#多线程那点事——信号量(Semaphore)

    信号量说简单点就是为了线程同步,或者说是为了限制线程能运行的数量。

    那它又是怎么限制线程的数量的哩?是因为它内部有个计数器,比如你想限制最多5个线程运行,那么这个计数器的值就会被设置成5,如果一个线程调用了这个Semaphore,那么它的计数器就会相应的减1,直到这个计数器变为0。这时,如果有另一个线程继续调用这个Semaphore,那么这个线程就会被阻塞。

    获得Semaphore的线程处理完它的逻辑之后,你就可以调用它的Release()函数将它的计数器重新加1,这样其它被阻塞的线程就可以得到调用了。

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading;

    namespace Semaphore1
    {
    class Program
    {
    //我设置一个最大允许5个线程允许的信号量
    //并将它的计数器的初始值设为0
    //这就是说除了调用该信号量的线程都将被阻塞
    static Semaphore semaphore = new Semaphore(0, 5);

    static void Main(string[] args)
    {
    for (int i = 1; i <= 5; i++)
    {
    Thread thread = new Thread(new ParameterizedThreadStart(work));

    thread.Start(i);
    }

    Thread.Sleep(1000);
    Console.WriteLine("Main thread over!");

    //释放信号量,将初始值设回5,你可以将
    //将这个函数看成你给它传的是多少值,计数器
    //就会加多少回去,Release()相当于是Release(1)
    semaphore.Release(5);
    }

    static void work(object obj)
    {
    semaphore.WaitOne();

    Console.WriteLine("Thread {0} start!",obj);

    semaphore.Release();
    }
    }
    }

    结果如下图所示,其它的线程只有等到主线程释放才会执行,因为我给信号量计数器的初始值是0,所以其它线程在主线程释放前都会被阻塞。而后,我在主线程直接用Release()函数将计数器置为5,所以5个线程可以同时得到执行。

    image

    另外,可以给信号量设置一个名称,这个名称是操作系统可见的,因此,可以使用这些信号量来协调跨进程边界的资源使用。

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading;

    namespace Semaphore2
    {
    class Program
    {
    static void Main(string[] args)
    {
    Semaphore seamphore = new Semaphore(5, 5, "SemaphoreExample");

    seamphore.WaitOne();
    Console.WriteLine("Seamphore 1");
    seamphore.WaitOne();
    Console.WriteLine("Seamphore 2");
    seamphore.WaitOne();
    Console.WriteLine("Seamphore 3");

    Console.ReadLine();
    seamphore.Release(3);
    }
    }
    }

    运行两个这样的程序,你讲看到这样的结果,在第二个运行的示例中,会将线程阻塞在第三个信号量上。

    image

  • 相关阅读:
    BZOJ 3196 二逼平衡树
    BZOJ 4241 历史研究
    Problem 71:Ordered fractions
    矿工安全生产
    Codeforces 771C:Bear and Tree Jumps
    Problem 77:Prime summations
    Problem 69:Totient maximum
    关于Euclid算法
    团体程序设计天梯赛-练习集
    埃蒙的时空航道
  • 原文地址:https://www.cnblogs.com/heqichang/p/2300301.html
Copyright © 2011-2022 走看看