【发布时间】:2015-11-10 15:48:06
【问题描述】:
我想写一个简单的 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));
}
最后一行有问题。这个向量不断增长,你知道任何管理它的正确方法吗?如何产生这些线程?是否有任何实现的数据结构或类似的东西来管理线程?我阅读了有关线程池的信息,但我认为这并不能解决这个问题。
【问题讨论】:
-
你一次又一次地重复推动相同的功能..
标签: c++ multithreading sockets