Skip to content

Commit 09f8a20

Browse files
authored
Fix iterator invalidation bug when stopping TCP server (#225)
1 parent 28a78a8 commit 09f8a20

File tree

1 file changed

+16
-2
lines changed

1 file changed

+16
-2
lines changed

trantor/net/TcpServer.cc

Lines changed: 16 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -148,7 +148,15 @@ void TcpServer::stop()
148148
if (loop_->isInLoopThread())
149149
{
150150
acceptorPtr_.reset();
151-
for (auto connection : connSet_)
151+
// copy the connSet_ to a vector, use the vector to close the
152+
// connections to avoid the iterator invalidation.
153+
std::vector<TcpConnectionPtr> connPtrs;
154+
connPtrs.reserve(connSet_.size());
155+
for (auto &conn : connSet_)
156+
{
157+
connPtrs.push_back(conn);
158+
}
159+
for (auto connection : connPtrs)
152160
{
153161
connection->forceClose();
154162
}
@@ -159,7 +167,13 @@ void TcpServer::stop()
159167
auto f = pro.get_future();
160168
loop_->queueInLoop([this, &pro]() {
161169
acceptorPtr_.reset();
162-
for (auto connection : connSet_)
170+
std::vector<TcpConnectionPtr> connPtrs;
171+
connPtrs.reserve(connSet_.size());
172+
for (auto &conn : connSet_)
173+
{
174+
connPtrs.push_back(conn);
175+
}
176+
for (auto connection : connPtrs)
163177
{
164178
connection->forceClose();
165179
}

0 commit comments

Comments
 (0)