Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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();
  }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
358 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...