信号量停止我的线程 [英] Semaphore halting my thread

查看:85
本文介绍了信号量停止我的线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面的我的代码在信号灯上停止.

代码正确创建线程.删除信号量代码后,它可以正确运行.

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

此处的实际代码:

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

推荐答案

由于没有可用的可用插槽,信号灯最初已关闭.在穿越 WaitOne()调用之前,必须有一些免费的东西.

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

这允许输入0,您需要将0修改为要允许的并发访问次数.

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

这篇关于信号量停止我的线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆