具有多线程的c++服务器
c++ server with multiple threads
我想写一个简单的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傲慢地表示,如果你认为你需要这个功能,你可能需要重新思考你的应用程序设计-我不同意。无论如何,你可以做的一件事就是使用线程池——它们会对你有所帮助。
相关文章:
- "unknown ca"自生成的 CA、证书和客户端/服务器
- 当我编译webrtc服务器时,Windows上只支持clang-cl
- 如何通过套接字将文本文件的内容从服务器发送到客户端
- 有没有办法知道Tracer是否成功地完全连接到了jaegerclientcpp中的jaeger后端服务器
- 从服务器传输到客户端的消息不会出现
- QTcpSocket在不阻塞GUI的情况下重新连接到服务器
- OpenSSL TLS服务器-使用客户端证书白名单
- 我正在开发服务器,ip作为参数传递不起作用
- 我可以与 python 服务器而不是 c++ 客户端建立 tcp/ip 套接字吗?
- 提升 Asio TCP 服务器 处理多个客户端
- 如何在 Minecraft 服务器上执行命令
- 调试编译的服务器在数据库打开时崩溃
- C++套接字客户端到 Python 服务器未创建连接
- 用于解析 win64 堆栈跟踪的命令行客户端(可以访问符号服务器)
- 将相机数据从服务器实时流式传输到客户端
- 为什么创建服务器后C++ httplib 库阻塞了我的主线程?
- 每个服务器请求的内存预算
- 如何将 Firebase 与基于 Linux 的客户端应用配合使用,以便与服务器进行双向消息通信
- 使用嵌入式猫鼬服务器托管应用程序
- NodeJs 服务器充斥着 UDP 广播,不发送响应