• Welcome to Valhalla Legends Archive.
 

recv() in infinite loop question

Started by nickolay, January 18, 2004, 10:30 PM

Previous topic - Next topic

nickolay

I would like to know if there is any other way in c++ to recieve (or wait to recive) data other than putting the recv function inside of an infinite loop and breaking out of it once the connection is closed. The problem with this is that it eats up 100% of CPU, which in my case in unacceptable.

Thank you in advance.

Raven


Kp

Quote from: nickolay on January 18, 2004, 10:30 PM
I would like to know if there is any other way in c++ to recieve (or wait to recive) data other than putting the recv function inside of an infinite loop and breaking out of it once the connection is closed. The problem with this is that it eats up 100% of CPU, which in my case in unacceptable.

It sounds like you're doing a nonblocking recv.  That's bad if you plan to spin on it.  Either make the socket blocking so that the OS puts you to sleep until data arrives, or sleep elsewhere until you know data to be ready.  If you're on a Unix system, use select() to monitor for data pending.  select() exists on Windows, but its implementation sucks horribly and you're much better off using a Windows specific alternative if you're working on Windows.  There're several options of varying desirability for Windows.  If you're interested in a breakdown, let me know.
[19:20:23] (BotNet) <[vL]Kp> Any idiot can make a bot with CSB, and many do!

Arta

Use WSACreateEvent, WaitForSingleObject, & WSAEnumNetworkEvents.

UserLoser.

I had a similar problem like this where It'd constantly use 99% CPU, but with more than one socket (BNLS, Bnet, BotNet) - I was using


WaitResult = MsgWaitForMultipleObjects(ConnectionCount - 1, events, false, INFINITE, QS_ALLINPUT);


With only one socket, I'm fine :-\

nickolay

#5
I've decided to use blocking sockets in multiple threads. Thank you everyone for the much-needed advice.

Adron

Multiple threads... Well, it works pretty ok, especially if the threads never have to talk to each other. It's not the best performance solution though.

The 99% cpu use sounds like it returned an error, or your code to handle the events was flawed and didn't reset them.

nickolay

You're correct about it returning an error. It turns out I wouldn't even pause after trying to recieve after I got an error. Also, I did get it so that the threads don't have to communicate in any way now.