具有多线程的c++服务器

c++ server with multiple threads

本文关键字:c++ 服务器 多线程      更新时间:2023-10-16

我想写一个简单的C++聊天服务器。简化:

         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
             }

主回路:

              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));
             }

我对最后一行有意见。这个矢量不断增长,你知道有什么合适的方法来管理它吗?如何生成这些线程?是否有任何实现的数据结构或类似的东西来管理线程?我读过关于线程池的文章,但我认为这并不能解决这个问题。

一种(正确的)设计可能是:

  • 管理连接队列的线程池
  • 重复接受套接字的侦听线程

Psuedo代码可能是:

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

task是实际的函数/函数对象/对象,它对套接字做一些有意义的事情,比如读取它的内容,将结果写入客户端,关闭套接字。

它将继续增长,因为这就是你所做的——你为每个连接创建一个线程。偶尔线程会退出,但您永远不会从这个向量中删除元素,因为您不是在连接线程。

最好的方法是自动连接向量中的所有可连接线程,但令我沮丧的是,posix完全缺乏这一功能——一次只能连接一个线程。Posix傲慢地表示,如果你认为你需要这个功能,你可能需要重新思考你的应用程序设计-我不同意。无论如何,你可以做的一件事就是使用线程池——它们会对你有所帮助。