代码改变世界

c# Semaphore(信号量)

2010-08-31 14:18  田志良  阅读(23986)  评论(0编辑  收藏  举报

信号量 Semaphore

类似互斥锁,但它可以允许多个线程同时访问一个共享资源

通过使用一个计数器来控制对共享资源的访问,如果计数器大于0,就允许访问,如果等于0,就拒绝访问。计数器累计的是“许可证”的数目,为了访问某个资源。线程必须从信号量获取一个许可证。

通常在使用信号量时,希望访问共享资源的线程将尝试获取一个许可证,如果信号量的计数器大于0,线程将获取一个许可证并将信号量的计数器减1,否则先线程将阻塞,直到获取一个许可证;当线程不再需要共享资源时,将释放锁拥有的许可证,并将许可证的数量加1,如果有其他的线程正在等待许可证,那么该线程将立刻获取许可证。

另外,允许同时访问的资源的进程数量是在创建信号量时指定的,如果创建一个允许进程访问的信号量数目为1,则该信号量就和互斥锁的用法一样。

Public Semaphore(int initialCount,int maximumCount)

initialCount指信号量许可证的初始值,maximumCount为最大值

获取许可证使用WaitOne()

不需要时释放使用 public int Release();或者public int Release(int  releaseCount);

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

using System.Threading;

namespace MyTTCon
{
    class mythread
    {
        public Thread thrd;
        //创建一个可授权2个许可证的信号量,且初始值为2
        static Semaphore sem = new Semaphore(2, 2);

        public mythread(string name)
        {
            thrd = new Thread(this.run);
            thrd.Name = name;
            thrd.Start();
        }
        void run()
        {
            Console.WriteLine(thrd.Name + "正在等待一个许可证……");
            //申请一个许可证
            sem.WaitOne();
            Console.WriteLine(thrd.Name + "申请到许可证……");
            for (int i = 0; i < 4 ; i++)
            {
                Console.WriteLine(thrd.Name + ": " + i);
                Thread.Sleep(1000);
            }
            Console.WriteLine(thrd.Name + " 释放许可证……");
            //释放
            sem.Release();
        }
    }

    class mysemaphore
    {
        public static void Main()
        {
            mythread mythrd1 = new mythread("Thrd #1");
            mythread mythrd2 = new mythread("Thrd #2");
            mythread mythrd3 = new mythread("Thrd #3");
            mythread mythrd4 = new mythread("Thrd #4");
            mythrd1.thrd.Join();
            mythrd2.thrd.Join();
            mythrd3.thrd.Join();
            mythrd4.thrd.Join();
        }
    } 
}