Lock around writes

This commit is contained in:
flamingcow
2019-05-09 20:24:59 -07:00
parent 19c390aa54
commit 31dd603873
2 changed files with 15 additions and 2 deletions

View File

@@ -54,6 +54,8 @@ const std::string_view& Request::GetBody() {
} }
void Request::WriteHeader(const std::string_view& name, const std::string_view& value) { void Request::WriteHeader(const std::string_view& name, const std::string_view& value) {
std::lock_guard<std::mutex> l(output_mu_);
CHECK(!body_written_); CHECK(!body_written_);
CHECK(out_buf_.Write(name)); CHECK(out_buf_.Write(name));
CHECK(out_buf_.Write(": ")); CHECK(out_buf_.Write(": "));
@@ -62,6 +64,8 @@ void Request::WriteHeader(const std::string_view& name, const std::string_view&
} }
void Request::WriteBody(const std::string_view& body) { void Request::WriteBody(const std::string_view& body) {
std::lock_guard<std::mutex> l(output_mu_);
if (!body_written_) { if (!body_written_) {
CHECK(out_buf_.Write("\n")); CHECK(out_buf_.Write("\n"));
body_written_ = true; body_written_ = true;
@@ -71,6 +75,8 @@ void Request::WriteBody(const std::string_view& body) {
} }
bool Request::Flush() { bool Request::Flush() {
std::lock_guard<std::mutex> l(output_mu_);
std::vector<iovec> vecs; std::vector<iovec> vecs;
auto header = OutputHeader(); auto header = OutputHeader();
@@ -82,12 +88,17 @@ bool Request::Flush() {
return false; return false;
} }
out_buf_.Commit(); out_buf_.Commit();
out_buf_.Consume();
return true; return true;
} }
bool Request::End() { bool Request::End() {
// Fully empty response not allowed std::lock_guard<std::mutex> l(output_mu_);
WriteBody("");
if (!body_written_) {
// Fully empty response not allowed
CHECK(out_buf_.Write("\n"));
}
std::vector<iovec> vecs; std::vector<iovec> vecs;

View File

@@ -1,5 +1,6 @@
#pragma once #pragma once
#include <mutex>
#include <unordered_map> #include <unordered_map>
#include "firebuf/buffer.h" #include "firebuf/buffer.h"
@@ -41,6 +42,7 @@ class Request {
firebuf::Buffer out_buf_; firebuf::Buffer out_buf_;
bool body_written_; bool body_written_;
std::mutex output_mu_;
}; };
} // namespace firecgi } // namespace firecgi