How to make a program not utilize 100% cpu?

倾然丶 夕夏残阳落幕 提交于 2019-12-06 06:07:50

Q: How to make a program not utilize 100% CPU?

A: Don't create a busy loop!!!!

Blocking is Good. There are lots of ways to accomplish "block until there's something to do". Including using an alarm signal or timer (poor, but a definite improvement), doing a socket read with a timeout (if you happen to be notified with a network socket) or using a Windows Event object with a timeout.

Failing all else, you can always use a "Sleep()". I would discourage using "Sleep" if you can avoid it - there are almost always much better design strategies. But it will keep you from a 100% CPU busy loop ;)

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

Addendum: you posted some code (thank you!)

You're using xxx.WaitOne().

Just use WaitOne() (a blocking call), with a timeout. This is an IDEAL solution: no busy loop, no "Sleep" required!

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

Put System.Threading.Thread.Sleep(100) (100 milliseconds sleep = time for system to do something else) in your infinite loops.

For the threads that send messages, when the queue is emtpy, use a 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
}

This way, you won't have 2 threads chewing up all of the CPU cycles all of the time

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!