From f57672b39093f4c174ada0c0a171057ab87e660e Mon Sep 17 00:00:00 2001 From: metsw24-max Date: Tue, 17 Nov 2026 08:38:13 +0530 Subject: [PATCH] take the request lock in open_stream_ before reusing the socket (#2669) * take the request lock in open_stream_ before reusing the socket * Hold the request lock only while open_stream_ takes the socket The handle owns the connection once the socket is transferred to it, so holding request_mutex_ while the stream wrote its request and read the response head only made requests on other threads wait for the stream. Also shorten the comments. --------- Co-authored-by: yhirose --- httplib.h | 2 ++ test/test.cc | 39 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 41 insertions(+) diff --git a/httplib.h b/httplib.h index 6d1d8e0f..c5a894b4 100644 --- a/httplib.h +++ b/httplib.h @@ -16062,6 +16062,8 @@ inline ClientImpl::StreamHandle ClientImpl::open_stream_(Request &req) { handle.connection_ = detail::make_unique(); { + // A request in flight uses socket_ without holding socket_mutex_ + std::lock_guard request_mutex_guard(request_mutex_); std::lock_guard guard(socket_mutex_); if (!socket_reusable()) { diff --git a/test/test.cc b/test/test.cc index de594452..010e30e7 100644 --- a/test/test.cc +++ b/test/test.cc @@ -24347,6 +24347,45 @@ TEST(OpenStreamPartialWriteTest, BodyIsWrittenWhole) { } #endif +TEST(OpenStreamConcurrencyTest, RequestInFlightKeepsItsConnection) { + std::promise slow_started; + auto slow_started_future = slow_started.get_future(); + + Server svr; + svr.Get("/slow", [&](const Request &, Response &res) { + slow_started.set_value(); + std::this_thread::sleep_for(std::chrono::milliseconds(200)); + res.set_content("slow", "text/plain"); + }); + svr.Get("/fast", [](const Request &, Response &res) { + res.set_content("fast", "text/plain"); + }); + + auto port = svr.bind_to_any_port(HOST); + std::thread t([&]() { svr.listen_after_bind(); }); + auto se = detail::scope_exit([&] { + svr.stop(); + t.join(); + }); + svr.wait_until_ready(); + + Client cli(HOST, port); + + std::string slow_body; + std::thread slow_thread([&] { + auto res = cli.Get("/slow"); + if (res) { slow_body = res->body; } + }); + slow_started_future.wait(); + + auto result = stream::Get(cli, "/fast"); + auto fast_body = result.is_valid() ? result.read_all() : std::string(); + slow_thread.join(); + + EXPECT_EQ("slow", slow_body); + EXPECT_EQ("fast", fast_body); +} + // Serves `response` to the single request `fn` makes with a fresh client. template static void with_single_response(const std::string &response, Fn fn) {