fix server crash on control client disconnect (quit, exit, bye)

This commit is contained in:
Johannes Pohl 2017-06-06 22:45:28 +02:00
parent fa9715684b
commit b56d656c32
3 changed files with 12 additions and 13 deletions

View file

@ -83,7 +83,10 @@ void ControlServer::onMessageReceived(ControlSession* connection, const std::str
{ {
if (it->get() == connection) if (it->get() == connection)
{ {
sessions_.erase(it); /// delete in a thread to avoid deadlock
auto func = [&](std::shared_ptr<ControlSession> s)->void{sessions_.erase(s);};
std::thread t(func, *it);
t.detach();
break; break;
} }
} }

View file

@ -45,8 +45,8 @@ void ControlSession::start()
std::lock_guard<std::recursive_mutex> activeLock(activeMutex_); std::lock_guard<std::recursive_mutex> activeLock(activeMutex_);
active_ = true; active_ = true;
} }
readerThread_ = new thread(&ControlSession::reader, this); readerThread_ = thread(&ControlSession::reader, this);
writerThread_ = new thread(&ControlSession::writer, this); writerThread_ = thread(&ControlSession::writer, this);
} }
@ -66,25 +66,21 @@ void ControlSession::stop()
socket_->close(ec); socket_->close(ec);
if (ec) logE << "Error in socket close: " << ec.message() << "\n"; if (ec) logE << "Error in socket close: " << ec.message() << "\n";
} }
if (readerThread_) if (readerThread_.joinable())
{ {
logD << "joining readerThread\n"; logD << "joining readerThread\n";
readerThread_->join(); readerThread_.join();
delete readerThread_;
} }
if (writerThread_) if (writerThread_.joinable())
{ {
logD << "joining writerThread\n"; logD << "joining writerThread\n";
messages_.abort_wait(); messages_.abort_wait();
writerThread_->join(); writerThread_.join();
delete writerThread_;
} }
} }
catch(...) catch(...)
{ {
} }
readerThread_ = NULL;
writerThread_ = NULL;
socket_ = NULL; socket_ = NULL;
logD << "ControlSession stopped\n"; logD << "ControlSession stopped\n";
} }

View file

@ -78,8 +78,8 @@ protected:
std::atomic<bool> active_; std::atomic<bool> active_;
mutable std::recursive_mutex activeMutex_; mutable std::recursive_mutex activeMutex_;
mutable std::recursive_mutex socketMutex_; mutable std::recursive_mutex socketMutex_;
std::thread* readerThread_; std::thread readerThread_;
std::thread* writerThread_; std::thread writerThread_;
std::shared_ptr<tcp::socket> socket_; std::shared_ptr<tcp::socket> socket_;
ControlMessageReceiver* messageReceiver_; ControlMessageReceiver* messageReceiver_;
Queue<std::string> messages_; Queue<std::string> messages_;