我制作了一个非常简单的C++套接字服务器。每次新客户端连接时,我都会尝试生成一个线程(这样就可以并行进行读取)。
void Server::start(void){
for(;;){
Logger::Log("Now accepting clients");
int client;
struct sockaddr_in client_addr;
size_t addr_size = sizeof(client_addr);
client = accept(this->m_socket, (sockaddr*)&client_addr, 0);
if(client != SOCKET_ERROR){
Logger::Log("New client connected!");
StateObject client_object(client, this);
this->clients.push_back(&client_object);
std::stringstream stream;
stream<<this->clients.size()<<" clients online";
Logger::Log(const_cast<char*>(stream.str().c_str()));
std::thread c_thread(std::bind(&StateObject::read, std::ref(client_object)));
//c_thread.join(); //if I join the child, new clients won't be accepted until the previous thread exits
}
}
}客户端类中的读取方法:
void StateObject::read(){
Logger::Log("Now reading");
for(;;){
int bytesReceived = recv(this->socket, buffer, 255, 0);
if(bytesReceived > 0){
Logger::Log(const_cast<char*>(std::string("Received: " + std::string(buffer).substr(0, bytesReceived)).c_str()));
}else if(bytesReceived == 0){
Logger::Log("Client gracefully disconnected");
break;
}else{
Logger::Log("Could not receive data from remote host");
break;
}
}
Server * server = reinterpret_cast<Server*>(parent);
server->removeClient(this);
}当前,在客户端连接之后,将引发异常:

为什么和何时触发中止?请注意,当子线程尚未加入主线程时会发生这种情况。在另一种情况下,“流”应该是同步的(当前客户端线程必须退出,以便循环能够继续接受下一个客户机)。
备注:
发布于 2014-03-01 15:52:11
您要么需要断开线程,要么在线程超出作用域之前加入它。否则,std::线程在其析构函数中调用std::终止。
http://www.cplusplus.com/reference/thread/thread/~thread/
https://stackoverflow.com/questions/22116467
复制相似问题