Skip to content

Commit

Permalink
Use atomic for joinStarted_ in AsyncScope
Browse files Browse the repository at this point in the history
Summary: `AcyncScope::remaining()` may be called from any thread, so we need to mark that `joinStarted_` can be accessed concurrently. Because we don't make any promises about the accuracy of `AsyncScope::remaining()` (i.e. it's value may change anytime) we use relaxed memory ordering.

Reviewed By: aforster

Differential Revision: D51368353

fbshipit-source-id: 274cdb51391c08d42fbc28cc6d0e16ebc8d63541
  • Loading branch information
h-friederich authored and facebook-github-bot committed Nov 21, 2023
1 parent df25370 commit 2fbd5cf
Showing 1 changed file with 8 additions and 4 deletions.
12 changes: 8 additions & 4 deletions folly/experimental/coro/AsyncScope.h
Original file line number Diff line number Diff line change
Expand Up @@ -186,7 +186,7 @@ class AsyncScope {

detail::Barrier barrier_{1};
std::atomic<bool> anyTasksStarted_{false};
bool joinStarted_{false};
std::atomic<bool> joinStarted_{false};
bool joined_{false};
bool throwOnJoin_{false};
folly::exception_wrapper maybeException_;
Expand All @@ -205,7 +205,9 @@ inline AsyncScope::~AsyncScope() {

inline std::size_t AsyncScope::remaining() const noexcept {
const std::size_t count = barrier_.remaining();
return joinStarted_ ? count : (count > 1 ? count - 1 : 0);
return joinStarted_.load(std::memory_order_relaxed)
? count
: (count > 1 ? count - 1 : 0);
}

template <typename Awaitable>
Expand Down Expand Up @@ -247,8 +249,10 @@ FOLLY_NOINLINE inline void AsyncScope::addWithSourceLoc(
}

inline Task<void> AsyncScope::joinAsync() noexcept {
assert(!joinStarted_ && "It is invalid to join a scope multiple times");
joinStarted_ = true;
assert(
!joinStarted_.load(std::memory_order_relaxed) &&
"It is invalid to join a scope multiple times");
joinStarted_.store(true, std::memory_order_relaxed);
co_await barrier_.arriveAndWait();
joined_ = true;
if (maybeException_.has_exception_ptr()) {
Expand Down

0 comments on commit 2fbd5cf

Please sign in to comment.