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();
  }
}
有帮助吗?

解决方案

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.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top