### C#多線程那點事——信號量(Semaphore)

`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();        }    }}`

`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);        }    }}`