Skip to content

[libcxx] Shared Mutex no longer holds the lock when calling notify_* on gates. #107876

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jan 13, 2025

Conversation

Brotcrunsher
Copy link
Contributor

Holding the associated lock while calling notify_* on a condition_variable is generally considered a pessimization, as the notified thread might "instantly" wake up, notice that it can't acquire the lock, and then goes back to sleep.

Note: This is my very first PR to the LLVM-Project. As such, it's possible that some kind of compiler extensions exist that render this unnecessary.

@Brotcrunsher Brotcrunsher requested a review from a team as a code owner September 9, 2024 15:20
Copy link

github-actions bot commented Sep 9, 2024

Thank you for submitting a Pull Request (PR) to the LLVM Project!

This PR will be automatically labeled and the relevant teams will be notified.

If you wish to, you can add reviewers by using the "Reviewers" section on this page.

If this is not working for you, it is probably because you do not have write permissions for the repository. In which case you can instead tag reviewers by name in a comment by using @ followed by their GitHub username.

If you have received no comments on your PR for a week, you can request a review by "ping"ing the PR by adding a comment “Ping”. The common courtesy "ping" rate is once a week. Please remember that you are asking for valuable time from other developers.

If you have further questions, they may be answered by the LLVM GitHub User Guide.

You can also ask questions in a comment on this PR, on the LLVM Discord or on the forums.

@llvmbot llvmbot added the libc++ libc++ C++ Standard Library. Not GNU libstdc++. Not libc++abi. label Sep 9, 2024
@llvmbot
Copy link
Member

llvmbot commented Sep 9, 2024

@llvm/pr-subscribers-libcxx

Author: None (Brotcrunsher)

Changes

Holding the associated lock while calling notify_* on a condition_variable is generally considered a pessimization, as the notified thread might "instantly" wake up, notice that it can't acquire the lock, and then goes back to sleep.

Note: This is my very first PR to the LLVM-Project. As such, it's possible that some kind of compiler extensions exist that render this unnecessary.


Full diff: https://github.com/llvm/llvm-project/pull/107876.diff

1 Files Affected:

  • (modified) libcxx/src/shared_mutex.cpp (+11-5)
diff --git a/libcxx/src/shared_mutex.cpp b/libcxx/src/shared_mutex.cpp
index 1a346dda027f8e..61808337369561 100644
--- a/libcxx/src/shared_mutex.cpp
+++ b/libcxx/src/shared_mutex.cpp
@@ -38,8 +38,10 @@ bool __shared_mutex_base::try_lock() {
 }
 
 void __shared_mutex_base::unlock() {
-  lock_guard<mutex> _(__mut_);
-  __state_ = 0;
+  {
+    lock_guard<mutex> _(__mut_);
+    __state_ = 0;
+  }
   __gate1_.notify_all();
 }
 
@@ -67,16 +69,20 @@ bool __shared_mutex_base::try_lock_shared() {
 }
 
 void __shared_mutex_base::unlock_shared() {
-  lock_guard<mutex> _(__mut_);
+  unique_lock<mutex> lk(__mut_);
   unsigned num_readers = (__state_ & __n_readers_) - 1;
   __state_ &= ~__n_readers_;
   __state_ |= num_readers;
   if (__state_ & __write_entered_) {
-    if (num_readers == 0)
+    if (num_readers == 0) {
+      lk.unlock();
       __gate2_.notify_one();
+    }
   } else {
-    if (num_readers == __n_readers_ - 1)
+    if (num_readers == __n_readers_ - 1) {
+      lk.unlock();
       __gate1_.notify_one();
+    }
   }
 }
 

Copy link
Member

@ldionne ldionne left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sorry for the much delayed review, this fell between the cracks. This seems correct to me since the lock only needs to be held when the variable is modified, but I'd also like someone else to validate this. @huixie90 perhaps?

…on gates.

Holding the associated lock while calling notify_* on a condition_variable is generally considered a pessimization, as the notified thread might "instantly" wake up, notice that it can't acquire the lock, and then goes back to sleep.
@ldionne
Copy link
Member

ldionne commented Jan 9, 2025

(I pushed to rebase onto the latest main and trigger CI)

@ldionne ldionne requested a review from huixie90 January 9, 2025 17:02
@huixie90 huixie90 self-assigned this Jan 9, 2025
Copy link
Member

@huixie90 huixie90 left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks! Thank implementation looks correct and should help with the performance. We delegate the underlying platform's pthread implementation (if there is one). I am not aware any optimisations like "if notifying thread holds the mutex that the cv is associated with, skip the wake up". I did a simple benchmark on Mac OS (with M4 CPU)

template <std::size_t NumReaders>
void test() {
  std::shared_mutex m;
  std::size_t writerCount = 0;
  std::array<std::size_t, NumReaders> readerCounts{};

  std::vector<std::jthread> threads;
  threads.reserve(NumReaders + 1);

  threads.emplace_back([&](std::stop_token st) {
    while (!st.stop_requested()) {
      std::unique_lock lock(m);
      writerCount++;
    }
  });

  for (std::size_t i = 0; i < NumReaders; ++i) {
    threads.emplace_back([&](std::stop_token st) {
      while (!st.stop_requested()) {
        std::shared_lock lock(m);
        readerCounts[i]++;
      }
    });
  }

  std::this_thread::sleep_for(2s);
  threads.clear();

  std::cout << "writerCount: " << writerCount << std::endl;
  for(std::size_t i = 0; i < NumReaders; ++i) {
    std::cout << "readerCounts[" << i << "]: " << readerCounts[i] << std::endl;
  }
}

Before your change, a typical output looks like

writerCount: 16492645
readerCounts[0]: 0
readerCounts[1]: 0
readerCounts[2]: 0
readerCounts[3]: 39
readerCounts[4]: 0

And with your fix , the output looks like

writerCount: 17607546
readerCounts[0]: 0
readerCounts[1]: 258
readerCounts[2]: 193
readerCounts[3]: 22
readerCounts[4]: 0

Both overall throughput and the fairness have improved

@ldionne ldionne merged commit ab6c89c into llvm:main Jan 13, 2025
62 checks passed
Copy link

@Brotcrunsher Congratulations on having your first Pull Request (PR) merged into the LLVM Project!

Your changes will be combined with recent changes from other authors, then tested by our build bots. If there is a problem with a build, you may receive a report in an email or a comment on this PR.

Please check whether problems have been caused by your change specifically, as the builds can include changes from many authors. It is not uncommon for your change to be included in a build that fails due to someone else's changes, or infrastructure issues.

How to do this, and the rest of the post-merge process, is covered in detail here.

If your change does cause a problem, it may be reverted, or you can revert it yourself. This is a normal part of LLVM development. You can fix your changes and open a new PR to merge them again.

If you don't get any reports, no action is required from you. Your changes are working as expected, well done!

kazutakahirata pushed a commit to kazutakahirata/llvm-project that referenced this pull request Jan 13, 2025
…hared_mutex (llvm#107876)

Holding the associated lock while calling notify_* on a
condition_variable is generally considered a pessimization, as the
notified thread might "instantly" wake up, notice that it can't acquire
the lock, and then goes back to sleep.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
libc++ libc++ C++ Standard Library. Not GNU libstdc++. Not libc++abi.
Projects
None yet
Development

Successfully merging this pull request may close these issues.

4 participants