C主要环路没有100%的CPU [英] C Main Loop without 100% cpu

查看:114
本文介绍了C主要环路没有100%的CPU的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#include <stdio.h>

int main() {
  while(!DONE) {
    /* check for stuff */
  }
  return 0;
}

以上code示例使用100%的CPU,直到DONE是真实的。我怎样才能实现一个循环,仅完成后终止的程序,但不使用100%的CPU?
现代语言使用类似App.ProcessMessages或类似的东西给操作系统控制的那一刻,然后返回到循环。

The above code sample uses 100% cpu until DONE is true. How can I implement a program that loops and only terminates when DONE, but which doesn't use 100% cpu? Modern languages use something like App.ProcessMessages or something like that to give the OS the control for the moment and then return to the loop.

我是新的C,明显...使用最新的GCC,Linux和Windows(便携式解决方案将是巨大的!)

I'm new at C, obviously... using latest GCC, linux and windows (a portable solution would be great!)

推荐答案

这取决于你想要这个循环里面做什么。

It depends what you want to do inside this loop.

如果您在循环中等待(即如果key pressed {做一些事情}那么你的机制会浪费系统资源给任何回报。更快的处理器只会让更多的空闲循环。这可以通过等待解决事件不只是睡觉,但preferably从而引发了一些有意义的事情可以做,比如一个事件,一个文件操作(标准输入也是一个文件)将是一个可移植的机制,这将让位给其他应用程序,直到数据可当你变得更加具体,可能需要潜入信号灯或这往往取决于操作系统的信号。一个抽象层可以解决这个问题。

If you are waiting inside the loop (i.e. if keypressed { do something} then your mechanism will waste system resources giving nothing in return. A faster processor will just make more idle loops. This can be solved by waiting for events Not just sleep, but preferably an event which triggers that something meaningful can be done. For instance, a file operation (stdin is also a file) would be a portable mechanism. This will give way to other applications until data is available. When you become more specific it may be required to dive into semaphores or signals which are often OS dependent. An abstraction layer can resolve this.

如果你正在做一些有用的东西(即处理大量的数据),那么100%的CPU负载只是意味着处理器以最有效的方式使用。你可以依靠操作系统让位给其他和可能更高优先级的任务。

If you are doing something useful (i.e. processing a lot of data), then 100% cpu load just means that the processor is used in the most efficient way. You can rely on the operating system to give way to other and possibly higher priority tasks.

使用像睡眠功能会降低CPU的使用率,但你的应用程序会慢一些。它需要得到可接受的性能和CPU负载之间的折衷。最大的执行速度会被你的睡眠参数由CPU速度定义,不再赘述。另外,如果电力是一个问题(即电池续航时间),那么这将要求CPU唤醒(睡眠周期结束时),没有要完成的工作;即系统资源的浪费不同

Using a function like sleep will lower cpu usage, but your application will be slower. It will require to get a tradeoff between acceptable performance and cpu load. The maximum execution speed will be defined by your sleep parameter, and no longer by the cpu speed. Also, if power is a concern (i.e. battery life time), then this will require the cpu to wakeup (end of sleep period) with no work to be done; i.e. a different waste of system resources.

这篇关于C主要环路没有100%的CPU的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆