Click here to Skip to main content
15,502,869 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
I have a following task:

"Ordinary" semaphore

Initialized to the number of available resources. operations: request () - waits until the resource is released, release () - releases the resource, numberAvailable () - returns number available resources, the n

which I tried to implement using Semaphore slim:

What I have tried:

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


however now, I need to do that using Monitor class, so I should create my own semaphore class. However I am a bit lost on how to change that
Posted
Updated 24-Oct-21 8:52am

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900