Skip to content

Commit 77431a3

Browse files
authored
Reduce futex usage in ParkingLot (#2907)
1 parent cffbd24 commit 77431a3

File tree

1 file changed

+7
-1
lines changed

1 file changed

+7
-1
lines changed

src/bthread/parking_lot.h

+7-1
Original file line numberDiff line numberDiff line change
@@ -40,11 +40,14 @@ class BAIDU_CACHELINE_ALIGNMENT ParkingLot {
4040
int val;
4141
};
4242

43-
ParkingLot() : _pending_signal(0) {}
43+
ParkingLot() : _pending_signal(0), _waiter_num(0) {}
4444

4545
// Wake up at most `num_task' workers.
4646
// Returns #workers woken up.
4747
int signal(int num_task) {
48+
if (_waiter_num.load(butil::memory_order_relaxed) == 0) {
49+
return 0;
50+
}
4851
_pending_signal.fetch_add((num_task << 1), butil::memory_order_release);
4952
return futex_wake_private(&_pending_signal, num_task);
5053
}
@@ -57,7 +60,9 @@ class BAIDU_CACHELINE_ALIGNMENT ParkingLot {
5760
// Wait for tasks.
5861
// If the `expected_state' does not match, wait() may finish directly.
5962
void wait(const State& expected_state) {
63+
_waiter_num.fetch_add(1, butil::memory_order_relaxed);
6064
futex_wait_private(&_pending_signal, expected_state.val, NULL);
65+
_waiter_num.fetch_sub(1, butil::memory_order_relaxed);
6166
}
6267

6368
// Wakeup suspended wait() and make them unwaitable ever.
@@ -68,6 +73,7 @@ class BAIDU_CACHELINE_ALIGNMENT ParkingLot {
6873
private:
6974
// higher 31 bits for signalling, LSB for stopping.
7075
butil::atomic<int> _pending_signal;
76+
butil::atomic<int> _waiter_num;
7177
};
7278

7379
} // namespace bthread

0 commit comments

Comments
 (0)