繁体   English   中英

使用 Monitor.Wait(obj) 和 Monitor.Pulse(obj) 实现信号量

[英]Implement Semaphore using Monitor.Wait(obj) and Monitor.Pulse(obj)

我有以下任务:

“普通”信号量

初始化为可用资源的数量。

操作:

request () - waits until the resource is released,
release () - releases the resource,
numberAvailable () - returns number available resources, the n  

我尝试使用Semaphore slim 来实现:

    class Program
    {
        private const int InitialCount = 2;
        private const int MaximumCount = 8;

        static void Main()
        {
            var semaphoreObject = new SemaphoreSlim(InitialCount, MaximumCount);
            var printerObject = new Printer();

            for (int i = 0; i < 20; ++i)
            {
                int j = i;
                Task.Factory.StartNew(() =>
                {
                    Request(semaphoreObject);
                    printerObject.Print(j);
                    Release(semaphoreObject);
                    NumberAvailable(semaphoreObject);
                });
            }
            Console.ReadLine();
        }

        private static void Request(SemaphoreSlim s)
        {
            s.Wait();
        }

        private static void Release(SemaphoreSlim s)
        {
            s.Release();
        }

        private static void NumberAvailable(SemaphoreSlim s)
        {
            Console.WriteLine($"Available resource: {s.CurrentCount}");
        }
    }

    class Printer
    {
        public void Print(int documentToPrint)
        {
            Console.WriteLine("Printing document: " + documentToPrint);
            Thread.Sleep(TimeSpan.FromSeconds(5));
        }
    }

但是现在,我需要使用 Monitor 类来做到这一点,所以我应该创建自己的信号量类。 但是我对如何改变它有点迷茫

我不会为你写代码,但这就是我要做的

  1. 在新的信号量类中,创建一个计数器。
  2. 在请求方法中使用监视器来:
    1. 增加计数
  3. 如果计数与允许的线程数相同,则使用另一个监视器锁定新对象
  4. 发布会上
    1. 减少第一个监视器内的计数
    2. 如果第二台显示器被锁定,请解锁它。

请记住,这不是最好的方法。 对生产代码使用内部类型。 这只是为了让您开始进行锻炼等。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM