简体   繁体   中英

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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