c#的多线程真是伤脑筋

我需要用多个并发线程来完成工作同时控制线程的数量不超过一个事先设定的最大值,遇到大麻烦了。

我是这样做的:

先运行一个调度线程,检查一个目前运行了多少个线程,如果少于最大值n个,则从一个队列里取出n个数据对象并启动相应的n个线程:
while (true)
{
    Monitor.Enter(mutex.QL);
    i=mutex.queue.Count;    //队列长度
    Monitor.Exit(mutex.QL);
    Monitor.Enter(mutex.TL);
    j=mutex.threadcount;    //线程数量
    Monitor.Exit(mutex.TL);

    if ((i==0)&&(j==0)) break;
    if (i!=0)
    {
     int diff=mutex.maxthread-j;
     diff=diff>i?i:diff;

     for (int idx=0; idx<diff; idx++)    //如果线程数量小于最大值并且队列不空则创建线程
     {
      Data data;
      data=(Data )(GetData());
      if (url==null) break;
      new Processor().startthread(data);
     }
    }
    Thread.Sleep(1000);
}

这是线程方法所在的业务对象:
class Processor
{
    private Data d;

    //启动线程
    public void startthread(Data data)
    {
        d=data;
        Thread thd=new Thread(new ThreadStart(proceed));
        thd.IsBackground=True;
        thd.Start();
    }
}

   //在工作线程里,开始运行的时候对线程数量计数器加1,退出时对计数器减1:
   private void proceed()
    {
       Monitor.Enter(mutex.TL);
       mutex.threadcount+=1;
       Monitor.Exit(mutex.TL);
       try
       {
            dostuff()...
       }
       catch (Exception ex)
       {
            logerr(ex.Message);
       }
       Monitor.Enter(mutex.TL);
       mutex.threadcount-=1;
       Monitor.Exit(mutex.TL);
    }
}

class mutex
{
    public static int threadcount;            //线程数量
    public static Queue queue=new Queue();    //数据队列
}

运行的时候发现cpu占用率很不稳定,大部分时间很低,但是会有阵发的占用100%的情况发生。而且,对于线程数量的控制也有问题,经常会看到创建的线程数量大于最大值的情况出现。头疼了两天了,还没找到办法。

ps: 最奇怪的是只开一个线程也会有占用cpu100%的情况出现,难道不是同步的问题?更迷糊了。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 5
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值