High CPU usage in basic C++ program
#1 Members - Reputation: 187
Posted 19 December 2012 - 03:09 PM
#2 Moderators - Reputation: 3293
Posted 19 December 2012 - 08:32 PM
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.
#3 Members - Reputation: 177
Posted 20 December 2012 - 12:40 PM
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.
Edited by crancran, 20 December 2012 - 12:42 PM.
#4 Moderators - Reputation: 3293
Posted 21 December 2012 - 12:26 PM
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."
#5 Banned - Reputation: 197
Posted 24 December 2012 - 05:15 PM
"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.






