信号量——Semaphore

作者:追风剑情 发布于:2017-9-20 21:31 分类:C#

可用来限制同时访问某个资源的线程数量。

示例

using System;
using System.Threading;

namespace SemaphoreTest
{
    class Program
    {
        static SimpleWaitLock slock;

        static void Main(string[] args)
        {
            //允许2条线程同时访问资源
            slock = new SimpleWaitLock(2, 10);

            Thread myThread;
            for (int i = 0; i < 10; i++)
            {
                myThread = new Thread(new ThreadStart(MyThreadProc));
                myThread.Name = String.Format("Thread{0}", i + 1);
                myThread.Start();
            }

            Console.ReadKey();
        }

        private static void MyThreadProc()
        {
            slock.Enter();
        }
    }

    public sealed class SimpleWaitLock : IDisposable
    {
        private Semaphore m_available;

        public SimpleWaitLock(int initialCount, int maximumCount)
        {
            m_available = new Semaphore(initialCount, maximumCount);
        }

        public void Enter()
        {
            m_available.WaitOne();//信号量减1
            Console.WriteLine("{0} Thread Enter", Thread.CurrentThread.Name);
            //模拟做些事情
            Thread.Sleep(1000);
            Leave();
        }

        public void Leave()
        {
            m_available.Release();//信号量加1
            Console.WriteLine("{0} Thread Level", Thread.CurrentThread.Name);
        }
        public void Dispose() { }
    }
}

运行测试

111111.png

标签: C#

Powered by emlog  蜀ICP备18021003号-1   sitemap

川公网安备 51019002001593号