From 8bd0813161fcb60871f415bd5b2512f2ec54b553 Mon Sep 17 00:00:00 2001 From: flamingcow Date: Thu, 9 May 2019 23:22:45 -0700 Subject: [PATCH] Simplify API with recursive mutex --- request.cc | 28 +++++++++++----------------- request.h | 13 ++++++------- 2 files changed, 17 insertions(+), 24 deletions(-) diff --git a/request.cc b/request.cc index 1f56970..5659452 100644 --- a/request.cc +++ b/request.cc @@ -54,7 +54,7 @@ const std::string_view& Request::GetBody() { } void Request::WriteHeader(const std::string_view& name, const std::string_view& value) { - std::lock_guard l(output_mu_); + std::lock_guard l(output_mu_); CHECK(!body_written_); CHECK(out_buf_.Write(name)); @@ -64,12 +64,17 @@ void Request::WriteHeader(const std::string_view& name, const std::string_view& } void Request::WriteBody(const std::string_view& body) { - std::lock_guard l(output_mu_); - WriteBodyLocked(body); + std::lock_guard l(output_mu_); + if (!body_written_) { + CHECK(out_buf_.Write("\n")); + body_written_ = true; + } + // TODO: make this able to span multiple packets + CHECK(out_buf_.Write(body)); } bool Request::Flush() { - std::lock_guard l(output_mu_); + std::lock_guard l(output_mu_); std::vector vecs; @@ -87,9 +92,9 @@ bool Request::Flush() { } bool Request::End() { - std::lock_guard l(output_mu_); + std::lock_guard l(output_mu_); - WriteBodyLocked(""); + WriteBody(""); std::vector vecs; @@ -120,15 +125,4 @@ Header Request::OutputHeader() { return Header(6, request_id_, out_buf_.ReadMaxLen()); } -void Request::WriteBodyLocked(const std::string_view& body) { - CHECK(!output_mu_.try_lock()); - - if (!body_written_) { - CHECK(out_buf_.Write("\n")); - body_written_ = true; - } - // TODO: make this able to span multiple packets - CHECK(out_buf_.Write(body)); -} - } // namespace firecgi diff --git a/request.h b/request.h index 14cf1d1..8436173 100644 --- a/request.h +++ b/request.h @@ -31,12 +31,11 @@ class Request { bool End(); template - void WriteMany(const std::string_view& first, Args... more); + void WriteBody(const std::string_view& first, Args... more); private: Header OutputHeader(); iovec OutputVec(); - void WriteBodyLocked(const std::string_view& body); Connection *conn_; uint16_t request_id_ = 0; @@ -46,14 +45,14 @@ class Request { firebuf::Buffer out_buf_; bool body_written_; - std::mutex output_mu_; + std::recursive_mutex output_mu_; }; template -void Request::WriteMany(const std::string_view& first, Args... more) { - std::lock_guard l(output_mu_); - WriteBodyLocked(first); - WriteMany(std::forward(more)...); +void Request::WriteBody(const std::string_view& first, Args... more) { + std::lock_guard l(output_mu_); + WriteBody(first); + WriteBody(more...); } } // namespace firecgi