我正在开发一个聊天服务器,我有一个问题.
如何安全地停止std :: thread?
这是非常容易的问题,像这样.
thread t(&func); t.join();
但是,如果func具有无限循环,则join不起作用.
这是我的来源.
void CServerSocket::AcceptRun(boost::asio::io_service &iosrv) { while (true) { auto sock = std::make_shared<boost::asio::ip::tcp::socket>(iosrv); m_Acceptor->accept(*sock); m_SocketList.push_back(std::make_shared<CConnectionSocket>(this,sock)); } }
和
CServerSocket::~CServerSocket() { CLogManager::WriteLog("Stopping Server..."); m_Acceptor->close(); m_Acceptor.reset(); // m_AcceptThread.detach(); This is right? CLogManager::WriteLog("Server Stoped!"); }
我很想知道
请帮帮我.
谢谢.
解决方法
我相当肯定接受将彻底退出,抛出异常,当你关闭接受者.你应该捕获异常以使线程正常退出:
void CServerSocket::AcceptRun(boost::asio::io_service &iosrv) try { // your loop here,unchanged } catch (std::exception const & ex) { // perhaps log the message,ex.what() }
然后在关闭接受者之后加入线程,但在销毁它之前:
CServerSocket::~CServerSocket() { CLogManager::WriteLog("Stopping Server..."); m_Acceptor->close(); m_AcceptThread.join(); CLogManager::WriteLog("Server Stopped!"); // No need to do anything else with m_Acceptor,assuming it's a smart pointer }
就个人而言,我会使用异步操作,除非有令人信服的理由使用多个线程.单线更容易处理.