开发者

How to reduce cpu usage in a c application?

开发者 https://www.devze.com 2023-02-18 15:49 出处:网络
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, i

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? 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.

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).

0

精彩评论

暂无评论...
验证码 换一张
取 消