Skip to content

Commit

Permalink
CHG: Improve locking strategy for completion token.
Browse files Browse the repository at this point in the history
  • Loading branch information
krisvanrens committed Sep 13, 2023
1 parent b120d71 commit 5c1e22e
Showing 1 changed file with 8 additions and 7 deletions.
15 changes: 8 additions & 7 deletions source/completion_token.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
#include <memory>
#include <mutex>
#include <optional>
#include <shared_mutex>
#include <stdexcept>

namespace ts {
Expand All @@ -14,19 +15,19 @@ inline namespace v1 {
namespace detail {

class completion_data final {
mutable std::mutex mutex_;
mutable std::condition_variable condition_;
bool completed_{false};
std::optional<std::exception_ptr> exception_;
mutable std::shared_mutex mutex_;
mutable std::condition_variable_any condition_;
bool completed_{false};
std::optional<std::exception_ptr> exception_;

public:
[[nodiscard]] bool is_completed() const {
std::unique_lock lock{mutex_};
std::shared_lock lock{mutex_};
return completed_;
}

void wait_for_completion() const {
std::unique_lock lock{mutex_};
std::shared_lock lock{mutex_};
condition_.wait(lock, [this] { return this->completed_; });
}

Expand All @@ -37,7 +38,7 @@ class completion_data final {
}

[[nodiscard]] const std::optional<std::exception_ptr>& exception() const {
std::unique_lock lock{mutex_};
std::shared_lock lock{mutex_};
return exception_;
}

Expand Down

0 comments on commit 5c1e22e

Please sign in to comment.