简体   繁体   English

如何减少AC应用中的CPU使用率?

[英]How to reduce cpu usage in a c application?

Im trying to do a simple server application, so i need to loop until theres a connection then loop again, etc... but when i do that, i get 50-100% cpu usage, while im using mutexes & conditions, is there any way to avoid this using posix threads (pthreads) in c? 我正在尝试做一个简单的服务器应用程序,所以我需要循环直到没有连接然后再循环,等等...但是当我这样做时,我得到了50-100%的cpu使用率,而我正在使用互斥体和条件,有什么办法可以避免在C中使用posix线程(pthreads)? if so, can you please give an example? 如果是这样,请您举个例子吗?

Without seeing your code, it's difficult to answer, but it sounds like you are using busy waiting . 没有看到您的代码,很难回答,但是听起来您正在使用忙等待 In pseudo-code: Busy waiting: 用伪代码:忙等待:

while (no connection) {
    check connection;
}

Better: 更好:

while (no connection) {
    sleep(100);
    check connection;
}

What you are doing is called busy waiting.. it isn't a good idea. 您正在做的事情被称为繁忙等待。这不是一个好主意。 If you are waiting for socket event, use a select function instead. 如果您正在等待套接字事件,请改用select函数。

Busy waiting is never a good solution. 繁忙的等待永远不是一个好的解决方案。 If you use the select, then your program will be waked when an event occured on a given file descriptor (or socket). 如果使用select,则当给定文件描述符(或套接字)上发生事件时,将唤醒程序。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM