mirror of
https://github.com/yhirose/cpp-httplib.git
synced 2026-11-17 19:30:54 +00:00
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 <yuji.hirose.bug@gmail.com>
This commit is contained in:
1 parent
654fd3546c
commit
f57672b390
2 files changed
+41
No files matched your search
@@ -16062,6 +16062,8 @@ inline ClientImpl::StreamHandle ClientImpl::open_stream_(Request &req) {
|
||||
handle.connection_ = detail::make_unique<ClientConnection>();
|
||||
|
||||
{
|
||||
// A request in flight uses socket_ without holding socket_mutex_
|
||||
std::lock_guard<std::recursive_mutex> request_mutex_guard(request_mutex_);
|
||||
std::lock_guard<std::mutex> guard(socket_mutex_);
|
||||
|
||||
if (!socket_reusable()) {
|
||||
|
||||
@@ -24347,6 +24347,45 @@ TEST(OpenStreamPartialWriteTest, BodyIsWrittenWhole) {
|
||||
}
|
||||
#endif
|
||||
|
||||
TEST(OpenStreamConcurrencyTest, RequestInFlightKeepsItsConnection) {
|
||||
std::promise<void> 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 <typename Fn>
|
||||
static void with_single_response(const std::string &response, Fn fn) {
|
||||
|
||||
Reference in new issue
Block a user