首页 文章

如何使程序不使用100%的CPU?

提问于
浏览
2

有5个线程在无限循环中运行 .

当队列不为空时,其中2个将发送消息 .

其中4人将在5分钟内继续发送心跳 .

其中一个是从另一个来源请求数据 .

当它使用100%的CPU时,我不能在窗口中使用任何其他应用程序 . 整个窗口变得很慢 .

EDIT: can sleep be put after WaitOne?

if(autoEvent.WaitOne())
{
}
else
{
}
Thread.Sleep(100);

Can sleep be put after subscriber.Recv() which is ZeroMQ ?

all threads i put a sleep if no Recv(), however there is one thread i do not dare to put a sleep in realtime datafeed thread which has only client.Send, will just one thread cause 100% ?

3 回答

  • 0

    在无限循环中放入System.Threading.Thread.Sleep(100)(100毫秒睡眠=系统执行其他操作的时间) .

  • 1

    对于发送消息的线程,当队列为emtpy时,请使用ResetEvent

    DeliverMessageThread_DoWork
    {
      while(true)
      {
        if(GetNextMessage() == null)
          MyAutoResetEvent.WaitOne(); // The thread will suspend here until the ARE is signalled
        else
        {
          DeliverMessage();
          Thread.Sleep(10); // Give something else a chance to do something
         }
      }
    }
    
    MessageGenerator_NewMessageArrived(object sender, EventArgs e)
    {
       MyAutoResetEvent.Set(); // If the deliver message thread is suspended, it will carry on now until there are no more messages to send
    }
    

    这样,您将不会有2个线程一直在占用所有CPU周期

  • 4

    问:如何使程序不使用100%CPU?

    答:不要创建繁忙的循环!!!!

    阻止是好的 . 有很多方法可以实现“阻止直到有事可做” . 包括使用报警信号或定时器(差,但有一定的改进),执行套接字读取超时(如果您恰好通过网络套接字通知)或使用超时的Windows事件对象 .

    失败一切,你总是可以使用"Sleep()" . 如果你能避免使用_560492,我会劝阻 - 几乎总有更好的设计策略 . 但它会让你远离100%CPU繁忙的循环;)

    =======================================

    附录:你发了一些代码(谢谢!)

    你正在使用xxx.WaitOne() .

    只需使用WaitOne()(阻塞调用),超时 . 这是一个理想的解决方案:没有繁忙的循环,不需要“睡眠”!

    http://msdn.microsoft.com/en-us/library/aa332441%28v=vs.71%29.aspx

相关问题