Skip to content

Commit

Permalink
Optimize Stream close flag
Browse files Browse the repository at this point in the history
It is more efficient to use atomic bool instead of
an ordinary boolean with mutex [0]

[0] https://stackoverflow.com/questions/15056237/which-is-more-efficient-basic-mutex-lock-or-atomic-integer
  • Loading branch information
testillano committed Jun 1, 2022
1 parent 098625f commit 34c61d3
Show file tree
Hide file tree
Showing 2 changed files with 7 additions and 6 deletions.
8 changes: 5 additions & 3 deletions include/ert/http2comm/Stream.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ SOFTWARE.
#pragma once

#include <mutex>
#include <atomic>
#include <sstream>
#include <memory>
#include <chrono>
Expand Down Expand Up @@ -80,7 +81,7 @@ class Stream : public std::enable_shared_from_this<Stream>
const nghttp2::asio_http2::server::response& res_;
std::shared_ptr<std::stringstream> request_;
Http2Server *server_;
bool closed_;
std::shared_ptr<std::atomic_bool> closed_;
std::chrono::microseconds reception_us_{}; // timestamp in microsecods

// Completes the nghttp2 transaction (res.end())
Expand All @@ -96,8 +97,9 @@ class Stream : public std::enable_shared_from_this<Stream>
Http2Server *server) : req_(req),
res_(res),
request_(request),
server_(server),
closed_(false) {}
server_(server) {
closed_ = std::make_shared<std::atomic_bool> (false);
}
Stream(const Stream&) = delete;
~Stream() = default;
Stream& operator=(const Stream&) = delete;
Expand Down
5 changes: 2 additions & 3 deletions src/Stream.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -181,7 +181,7 @@ void Stream::commit(unsigned int statusCode,
self->res_.io_service().post([self, statusCode, headers, responseBody]()
{
std::lock_guard<std::mutex> lg(self->mutex_);
if (self->closed_)
if (self->closed_->load())
{
return;
}
Expand All @@ -197,8 +197,7 @@ void Stream::commit(unsigned int statusCode,

void Stream::close()
{
std::lock_guard<std::mutex> guard(mutex_);
closed_ = true;
closed_->store(true);
}

}
Expand Down

0 comments on commit 34c61d3

Please sign in to comment.