Sleep(零)还是非常占用CPU
Sleep(0)还是非常占用CPU
本来想让一个线程没任务时就睡眠,使用Sleep(0)还是非常占用CPU,郁闷啊
------解决方案--------------------
那就sleep(10)呗
------解决方案--------------------
看起来像是线程池的理想使用场景啊
------解决方案--------------------
Sleep(0) 表示 线程 主动 放弃,剩余的 时间片,但 线程 还是 会被 调度。
等待 event 可能 会 好些。
------解决方案--------------------
可以采用生产者/消费者模型,当没有任务的时候消费者线程自动挂起,等生产者生产了任务后,消费者线程又可以继续执行。
------解决方案--------------------
呵呵,在实际的编程中,如果出现占用CPU居高不下的情况时,都是Sleep(1)。Sleep(10)对系统的性能有一定的影响。Sleep(1)是有据可查的。
------解决方案--------------------
Sleep(0)放弃本线程余下时间片
用于等待事件,最好不要使用Sleep函数,而是用内核的事件对象。
------解决方案--------------------
如果有通知机制, 那么事件通知等是比较好的做法.
如果没有这样的机制, 那只能通过Sleep这样的函数去延时, 轮询查看标记.
------解决方案--------------------
Sleep的时间是交出去的时间,假如while循环以及内部代码占1毫秒,这样
while(1)
{
Sleep(1);
}
相当于交出50%的时间。和你循环中代码多少有关。Sleep时间越长CPU占用越少,但是响应间隔越长。
------解决方案--------------------
“Notice the call to Sleep at the end of the loop. I’ve heard quite a bit of debate about the relative merits of Sleep(0) versus Sleep(1) for giving up your time slice. Here’s what the documentation says: “A value of zero causes the thread to relinquish the remainder of its time slice to any other thread of equal priority that is ready to run.” This means that if other threads aren’t quite ready or aren’t of equal priority, they won’t run. I’ve seen tests indicating that Sleep(1) is often a more effective way of yielding.”
本来想让一个线程没任务时就睡眠,使用Sleep(0)还是非常占用CPU,郁闷啊
------解决方案--------------------
那就sleep(10)呗
------解决方案--------------------
看起来像是线程池的理想使用场景啊
------解决方案--------------------
Sleep(0) 表示 线程 主动 放弃,剩余的 时间片,但 线程 还是 会被 调度。
等待 event 可能 会 好些。
------解决方案--------------------
可以采用生产者/消费者模型,当没有任务的时候消费者线程自动挂起,等生产者生产了任务后,消费者线程又可以继续执行。
------解决方案--------------------
呵呵,在实际的编程中,如果出现占用CPU居高不下的情况时,都是Sleep(1)。Sleep(10)对系统的性能有一定的影响。Sleep(1)是有据可查的。
------解决方案--------------------
Sleep(0)放弃本线程余下时间片
用于等待事件,最好不要使用Sleep函数,而是用内核的事件对象。
------解决方案--------------------
如果有通知机制, 那么事件通知等是比较好的做法.
如果没有这样的机制, 那只能通过Sleep这样的函数去延时, 轮询查看标记.
------解决方案--------------------
Sleep的时间是交出去的时间,假如while循环以及内部代码占1毫秒,这样
while(1)
{
Sleep(1);
}
相当于交出50%的时间。和你循环中代码多少有关。Sleep时间越长CPU占用越少,但是响应间隔越长。
------解决方案--------------------
“Notice the call to Sleep at the end of the loop. I’ve heard quite a bit of debate about the relative merits of Sleep(0) versus Sleep(1) for giving up your time slice. Here’s what the documentation says: “A value of zero causes the thread to relinquish the remainder of its time slice to any other thread of equal priority that is ready to run.” This means that if other threads aren’t quite ready or aren’t of equal priority, they won’t run. I’ve seen tests indicating that Sleep(1) is often a more effective way of yielding.”