Valhalla Legends Forums Archive | C/C++ Programming | recv() in infinite loop question

AuthorMessageTime
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.
January 19, 2004, 4:30 AM
Raven
Queing, scoping?
January 19, 2004, 6:27 AM
Kp
[quote author=nickolay link=board=30;threadid=4791;start=0#msg40108 date=1074486651]
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.[/quote]

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.
January 19, 2004, 6:28 AM
Arta
Use WSACreateEvent, WaitForSingleObject, & WSAEnumNetworkEvents.
January 19, 2004, 9:01 AM
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

[code]
WaitResult = MsgWaitForMultipleObjects(ConnectionCount - 1, events, false, INFINITE, QS_ALLINPUT);
[/code]

With only one socket, I'm fine :-\
January 19, 2004, 5:05 PM
nickolay
I've decided to use blocking sockets in multiple threads. Thank you everyone for the much-needed advice.
January 19, 2004, 5:43 PM
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.
January 19, 2004, 8:17 PM
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.
January 20, 2004, 11:57 AM

Search