Question

My code below halts on the semaphore.

Code creates the thread correctly. It runs correctly when the semaphore code is removed.

How do I make my semaphore block the code section, this case is just a loop, then release the semaphore when the loop is done.

lock
  loop
un-lock

actual code here:

using System.IO;
using System;
using System.Threading;

public class Program
{
   public static Semaphore sema;

   static void Main()
   {
      sema = new Semaphore(0, 2);

      Work w = new Work();
      Thread t = new Thread(w.doWork);
      t.Start(null);
   }
}

public class Work
{
   public void doWork(object data)
   {
      Program.sema.WaitOne();

      for(int i = 0; i < 10; i++)
          Console.WriteLine("I made it");

      Program.sema.Release();
  }
}
Was it helpful?

Solution

The semaphore is initially closed because there are no free slots available. There must be some free before you are able to cross the WaitOne() call.

sema = new Semaphore(0, 2);

This is allowing 0 enters, you need to modify 0 to the number of concurrent access you want to allow.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top