简体   繁体   中英

c++ server with multiple threads

I want to write a simple C++ chat server. Simplifying:

         void clientThread(int sock){
              // receives data on socket and sends to all other client's 
        //sockets which are held in a vector, when received data<0 thread is 
   // finished and client is removed from a vector
             }

Main loop:

              vector<thread> th;
              while(1){
                memset(&rcvAddr,0,sizeof(sockaddr_in));
                sock=accept(connectSocket,NULL,(socklen_t*)&addrLength);
                cout << "client connected from: " << inet_ntoa(rcvAddr.sin_addr)<< endl;
                if(sock<0)
                    continue;
                mtx.lock();
                clientDescriptors.push_back(sock);
                mtx.unlock();
                th.pushback(thread(&server::clientThread,this,sock));
             }

And I have a problem with the last line. This vector constantly grows, do you know any proper way to manage this? How to spawn these threads? Are there any implemented data structures, or something like this, to manage threads? I read about thread Pool, but I think this does not solve this problem.

One (proper) design may be :

  • A thread Pool which manages a connections queue
  • A listening thread which accepting Sockets repeatedly

a Psuedo code may be :

main:
  launch thread pool
  launch the listening thread
  block until server is not neaded

listening thread routine:
  while true
    accept a client socket
    build a task out of the client socket 
    push the task into the connection queue

the task is the actual function/function object/object which does something meaningfull with the socket, like reading it's content, write result to client, close the socket.

It is going to keep growing, because this is what you do - you create a thread for every connection. Occasionally threads exit, but you never get to removing elements from this vector, since you are not joining threads.

Best thing to do would be to join all joinable threads from the vector automatically, but to my ongoing dismay posix completely lacks this feature - you can only join one thread at a time. Posix arrogantly states that If you believe you need this functionality, you probably need to rethink your application design. - which I do not agree with. On any rate, one thing you can do is to use thread pools - they are going to help you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM