Reputation: 13839
I'm working on a Client-Server project. It should be able to handle multiple (>1000) client connections.
The main skeleton of my server-side waiting loop looks like this:
while(server->running)
{
// If I remove this, my CPU use will be very intensive
// but putting 10 milliseconds sleep will cause a significant delay
// What's is the best practice?
boost::this_thread::sleep(boost::posix_time::milliseconds(10));
if (server->connectionQueue.empty())
continue;
Connection* conn = server->connectionQueue.front();
server->connectionQueue.pop();
Stream* stream = conn->HandleData();
// More steps if needed here
server->connectionQueue.push(conn);
}
My questions are:
Currently I'm using one waiting loop for all connections. Is this correct? or what's the best practice? Should I use a waiting loop for each connection?
If I remove the thread::sleep
, my CPU use will be very intensive. But putting 10 milliseconds sleep will cause a significant delay, especially, if there are multiple connections. So what's is the best practice?
I googled, and found something called FD_ISSET
: http://linux.die.net/man/3/fd_isset
/* According to POSIX.1-2001 */ #include <sys/select.h> /* According to earlier standards */ #include <sys/time.h> #include <sys/types.h> #include <unistd.h> int select(int nfds, fd_set *readfds, fd_set *writefds, fd_set *exceptfds, struct timeval *timeout); void FD_CLR(int fd, fd_set *set); int FD_ISSET(int fd, fd_set *set); void FD_SET(int fd, fd_set *set); void FD_ZERO(fd_set *set); #define _XOPEN_SOURCE 600 #include <sys/select.h> int pselect(int nfds, fd_set *readfds, fd_set *writefds, fd_set *exceptfds, const struct timespec *timeout, const sigset_t *sigmask);
But I don't know how to use? How can I use it for my Socket File Descriptor?
Not sure If I made myself clear.
Upvotes: 3
Views: 1000
Reputation: 6473
I would recommend you have one main loop and use select()
to manage your connection and listening sockets.
Either man select_tut
or visit http://beej.us/guide/bgnet/ (or both)
Upvotes: 1