Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
368 views
in Technique[技术] by (71.8m points)

c# - Semaphore halting my thread

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

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

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...