High CPU usage in basic C++ program

Started by
3 comments, last by wood_brian 11 years, 3 months ago
Hi, I am using ThreadLib from Ron Pentons MUD programming example. I have 2 threads in my program, one which recieves messages and one which sends messages. I create both of these threads(each has an infinite loop) and I also make sure to yieldThread() in my main loop. I end up with 50%cpu usage, isn't this a bit high? It does only run at around 13% on a better machine, but shouldn't it be closer to 0 than that?
Advertisement
"yield thread" only yields until there is no other thread that wants the CPU, then you get the CPU back again.

You need to use a blocking primitive, like select() or sleep(), to actually reduce CPU usage. I recommend select(). Also, multiple threads is not recommended in the beginning of network programming. And, in fact, is often not needed at all.
enum Bool { True, False, FileNotFound };
To add to what hplus0603 said, if you put your network connection into non-blocking mode, you can use select() and poll for data each loop and handle it accordingly. In a well structured design, networking really should be abstracted away to the point that if you decide to move networking to a separate thread later on, the impact to the simulation would be very minimal and non-invasive to change.

But if you want to use a separate thread, you can use asynchronous/non-blocking socket IO to handle reads/writes in a single thread outside your logic thread. This way the problem manifests itself to a simple problem of synchronizing a queue of messages between the logic/network threads for sending/receiving. But in most cases, this isn't really necessary and by avoiding it reduces the complexity of your game logic iterations.

if you put your network connection into non-blocking mode, you can use select() and poll for data each loop and handle it accordingly

You can do that even with blocking sockets. That's the whole point of select(): When select() says a file descriptor is "ready" for reading or writing, it GUARANTEES that the next call to recv() or send() will not block, even if the socket is "blocking."

enum Bool { True, False, FileNotFound };
"yield thread" only yields until there is no other thread that wants the CPU, then you get the CPU back again.

You need to use a blocking primitive, like select() or sleep(), to actually reduce CPU usage. I recommend select(). Also, multiple threads is not recommended in the beginning of network programming. And, in fact, is often not needed at all.

I switched from using select to poll in a couple of programs a few months ago. The interface of poll is easier to work with.

This topic is closed to new replies.

Advertisement