如何使程序不使用100%cpu? [英] How to make a program not utilize 100% cpu?
问题描述
有5个线程无限循环运行.
There are 5 threads running in an infinite loop.
其中2个将在队列不为空时发送消息.
2 of them will send messages when queue is not empty.
其中4个将在5分钟内继续发送心跳.
4 of them will keep sending heartbeat within 5 minutes.
其中1个是从其他来源请求数据.
1 of them is to request data from another source.
当它使用100%的CPU时,我不能在窗口中使用任何其他应用程序.整个窗口变得非常慢.
When it utilizes 100% of the CPU, I can not use any other applications in the window. The whole window becomes very slow.
可以在WaitOne之后入睡吗?
if(autoEvent.WaitOne())
{
}
else
{
}
Thread.Sleep(100);
可以将睡眠置于Subscriber.Recv()之后,它是ZeroMQ吗?
如果没有Recv(),所有线程我都会进入睡眠状态,但是有一个线程我不敢在只有client.Send的实时数据馈送线程中进入睡眠状态,只有一个线程会导致100%吗?
推荐答案
问:如何使程序不使用100%CPU?
Q: How to make a program not utilize 100% CPU?
A:不要创建繁忙的循环!!!!
A: Don't create a busy loop!!!!
封锁是件好事.有很多方法可以完成阻止,直到有事情要做".包括使用警报信号或计时器(较差,但有一定改进),使用超时读取套接字(如果您恰巧收到网络套接字通知)或使用带有超时的Windows事件对象.
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.
如果其他所有操作失败,则始终可以使用"Sleep()".如果可以避免,我不鼓励使用睡眠"-几乎总是有更好的设计策略.但这将使您摆脱100%的CPU繁忙循环;)
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!)
您正在使用xxx.WaitOne().
You're using xxx.WaitOne().
只需使用带有超时的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
这篇关于如何使程序不使用100%cpu?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!