user502230
user502230

Reputation:

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?

Upvotes: 0

Views: 1295

Answers (2)

Heisenbug
Heisenbug

Reputation: 39164

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

Upvotes: 3

nfechner
nfechner

Reputation: 17525

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;
}

Upvotes: 4

Related Questions