Skip to content

Commit ab6c89c

Browse files
authored
[libcxx] Don't hold the lock when calling notify_* on gates in std::shared_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.
1 parent 7378afd commit ab6c89c

File tree

1 file changed

+11
-5
lines changed

1 file changed

+11
-5
lines changed

libcxx/src/shared_mutex.cpp

Lines changed: 11 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -38,8 +38,10 @@ bool __shared_mutex_base::try_lock() {
3838
}
3939

4040
void __shared_mutex_base::unlock() {
41-
lock_guard<mutex> _(__mut_);
42-
__state_ = 0;
41+
{
42+
lock_guard<mutex> _(__mut_);
43+
__state_ = 0;
44+
}
4345
__gate1_.notify_all();
4446
}
4547

@@ -67,16 +69,20 @@ bool __shared_mutex_base::try_lock_shared() {
6769
}
6870

6971
void __shared_mutex_base::unlock_shared() {
70-
lock_guard<mutex> _(__mut_);
72+
unique_lock<mutex> lk(__mut_);
7173
unsigned num_readers = (__state_ & __n_readers_) - 1;
7274
__state_ &= ~__n_readers_;
7375
__state_ |= num_readers;
7476
if (__state_ & __write_entered_) {
75-
if (num_readers == 0)
77+
if (num_readers == 0) {
78+
lk.unlock();
7679
__gate2_.notify_one();
80+
}
7781
} else {
78-
if (num_readers == __n_readers_ - 1)
82+
if (num_readers == __n_readers_ - 1) {
83+
lk.unlock();
7984
__gate1_.notify_one();
85+
}
8086
}
8187
}
8288

0 commit comments

Comments
 (0)