首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >C++ winsockets线程问题

C++ winsockets线程问题
EN

Stack Overflow用户
提问于 2014-03-01 15:44:14
回答 1查看 43关注 0票数 0

我制作了一个非常简单的C++套接字服务器。每次新客户端连接时,我都会尝试生成一个线程(这样就可以并行进行读取)。

代码语言:javascript
复制
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
        }
    }
}

客户端类中的读取方法:

代码语言:javascript
复制
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);
}

当前,在客户端连接之后,将引发异常:

为什么和何时触发中止?请注意,当子线程尚未加入主线程时会发生这种情况。在另一种情况下,“流”应该是同步的(当前客户端线程必须退出,以便循环能够继续接受下一个客户机)。

备注:

  • 由于我与Windows绑定,我无法分叉子任务--我也不是Cygwin的粉丝。异步win32方法似乎会使事情复杂化,这就是我为什么要避免它们的原因。
  • C++ std::线程引用
  • 已通过Telnet进行了测试。
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2014-03-01 15:52:11

您要么需要断开线程,要么在线程超出作用域之前加入它。否则,std::线程在其析构函数中调用std::终止。

http://www.cplusplus.com/reference/thread/thread/~thread/

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/22116467

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档