chenBright commented on code in PR #3774:
URL: https://github.com/apache/brpc/pull/3774#discussion_r4729530848
##########
src/bthread/timer_thread.cpp:
##########
@@ -249,18 +285,24 @@ TimerThread::TaskId TimerThread::schedule(
const Bucket::ScheduleResult result =
_buckets[butil::fmix64(pthread_numeric_id()) % _options.num_buckets]
.schedule(fn, arg, abstime);
- if (result.earlier) {
+ if (result.earlier || result.became_nonempty) {
bool earlier = false;
const int64_t run_time = butil::timespec_to_microseconds(abstime);
{
BAIDU_SCOPED_LOCK(_mutex);
- if (run_time < _nearest_run_time) {
+ if (result.earlier && run_time < _nearest_run_time) {
_nearest_run_time = run_time;
- ++_nsignals;
earlier = true;
}
+ // An empty-to-nonempty transition is a publication event even
+ // when its task is later than the heap minimum. The timer
+ // snapshots this sequence before polling buckets, preventing a
+ // stale empty-hint read from being followed by an indefinite wait.
+ if (earlier || result.became_nonempty) {
+ ++_nsignals;
+ }
}
- if (earlier) {
+ if (earlier || result.became_nonempty) {
futex_wake_private(&_nsignals, 1);
Review Comment:
Adding the empty-bucket wakeup here invalidates the premise of
`periodic_wakeup_drains_buckets`. The late task it submits can now wake the
thread itself, so `_npending == kN + 1` can hold even if the 50 ms wait limit
is removed.
##########
test/bthread_timer_thread_unittest.cpp:
##########
@@ -293,6 +298,207 @@ TEST(TimerThreadTest, schedule_and_unschedule_in_task) {
static void noop_routine(void*) {}
+void count_routine(void* arg) {
+ static_cast<std::atomic<int>*>(arg)->fetch_add(1,
+ std::memory_order_release);
+}
+
+class TimerThreadStopGuard {
+public:
+ explicit TimerThreadStopGuard(bthread::TimerThread* timer_thread)
+ : _timer_thread(timer_thread) {}
+
+ ~TimerThreadStopGuard() {
+ _timer_thread->stop_and_join();
+ }
+
+private:
+ bthread::TimerThread* _timer_thread;
+};
+
+class TimerWaitGate {
+public:
+ void arrive() {
+ std::unique_lock<std::mutex> lock(_mutex);
+ const int arrival = ++_arrivals;
+ _cv.notify_all();
+ if (arrival > 2) {
+ return;
+ }
+ _cv.wait(lock, [this, arrival] { return _released >= arrival; });
+ }
+
+ bool wait_for_arrivals(int target) {
+ std::unique_lock<std::mutex> lock(_mutex);
+ return _cv.wait_for(lock, std::chrono::seconds(1), [this, target] {
+ return _arrivals >= target;
+ });
+ }
+
+ void release(int arrival) {
+ std::lock_guard<std::mutex> lock(_mutex);
+ _released = std::max(_released, arrival);
+ _cv.notify_all();
+ }
+
+ void release_all() { release(std::numeric_limits<int>::max()); }
+
+ ~TimerWaitGate() { release_all(); }
+
+private:
+ std::mutex _mutex;
+ std::condition_variable _cv;
+ int _arrivals = 0;
+ int _released = 0;
+};
+
+void block_before_timer_wait(void* arg) {
+ static_cast<TimerWaitGate*>(arg)->arrive();
+}
+
+class ScopedTimerWaitHook {
+public:
+ ScopedTimerWaitHook(bthread::TimerThread* timer_thread,
+ TimerWaitGate* gate)
+ : _timer_thread(timer_thread) {
+ _timer_thread->_before_wait_hook = block_before_timer_wait;
+ _timer_thread->_before_wait_hook_arg = gate;
+ }
+
+ ~ScopedTimerWaitHook() {
+ _timer_thread->_before_wait_hook = nullptr;
+ _timer_thread->_before_wait_hook_arg = nullptr;
+ }
+
+private:
+ bthread::TimerThread* _timer_thread;
+};
+
+class TimerThreadHookStopGuard {
+public:
+ TimerThreadHookStopGuard(bthread::TimerThread* timer_thread,
+ TimerWaitGate* gate)
+ : _timer_thread(timer_thread), _gate(gate) {}
+
+ ~TimerThreadHookStopGuard() {
+ _gate->release_all();
+ _timer_thread->stop_and_join();
+ }
+
+private:
+ bthread::TimerThread* _timer_thread;
+ TimerWaitGate* _gate;
+};
+
+TEST(TimerThreadTest, sparse_buckets_execute_tasks) {
+ bthread::TimerThread timer_thread;
+ bthread::TimerThreadOptions options;
+ options.num_buckets = 1024;
+ ASSERT_EQ(0, timer_thread.start(&options));
+
+ std::atomic<int> completed(0);
+ TimerThreadStopGuard stop_timer(&timer_thread);
+ const int kTasks = 64;
+ for (int i = 0; i < kTasks; ++i) {
+ ASSERT_NE(bthread::TimerThread::INVALID_TASK_ID,
+ timer_thread.schedule(count_routine, &completed,
+ butil::microseconds_from_now(1)));
+ for (int retry = 0;
+ retry < 1000 && completed.load(std::memory_order_acquire) <= i;
+ ++retry) {
+ bthread_usleep(1000);
+ }
+ ASSERT_EQ(i + 1, completed.load(std::memory_order_acquire));
+ }
+}
+
+TEST(TimerThreadTest, later_empty_bucket_publication_survives_stale_hint) {
+ bthread::TimerThread timer_thread;
+ bthread::TimerThreadOptions options;
+ options.num_buckets = 1;
+ std::atomic<int> completed(0);
+ TimerWaitGate gate;
+ ScopedTimerWaitHook wait_hook(&timer_thread, &gate);
+ // Construct this last: its destructor releases the hook gate and joins
+ // the timer before the hook or gate can be destroyed.
+ TimerThreadHookStopGuard stop_timer(&timer_thread, &gate);
+ ASSERT_EQ(0, timer_thread.start(&options));
+
+ // Stop the timer at its first empty wait. After it is released, scheduling
+ // the anchor wakes it and moves the anchor into the private heap.
+ ASSERT_TRUE(gate.wait_for_arrivals(1));
+ gate.release(1);
+ ASSERT_NE(bthread::TimerThread::INVALID_TASK_ID,
+ timer_thread.schedule(count_routine, &completed,
+ butil::milliseconds_from_now(200)));
+
+ // The second gate is after the timer has scanned the empty bucket and
+ // selected the anchor as its heap deadline. The later task therefore does
+ // not change _nearest_run_time. It must still publish a wake sequence,
+ // otherwise this scan-to-wait window can lose the bucket publication.
+ ASSERT_TRUE(gate.wait_for_arrivals(2));
+ int signals_before;
+ {
+ BAIDU_SCOPED_LOCK(timer_thread._mutex);
+ signals_before = timer_thread._nsignals;
+ }
+ ASSERT_NE(bthread::TimerThread::INVALID_TASK_ID,
+ timer_thread.schedule(count_routine, &completed,
+ butil::milliseconds_from_now(400)));
+ {
+ BAIDU_SCOPED_LOCK(timer_thread._mutex);
+ EXPECT_EQ(signals_before + 1, timer_thread._nsignals);
+ }
+ // Model a legal stale false from the atomic fast-path load. The task stays
+ // linked in the bucket, and the publication protocol must ensure a later
+ // scan consumes it instead of leaving the timer asleep indefinitely.
+ timer_thread.force_empty_bucket_hint_once_for_test(0);
+ gate.release(2);
+
+ ASSERT_TRUE(WaitUntil([&completed] {
+ return completed.load(std::memory_order_acquire) == 2;
Review Comment:
By the time the second gate is reached, the old implementation has already
fetched the wait sequence number, so posting a task here cannot detect a
regression that moves the snapshot back to the end of the scan.
`force_empty_bucket_hint_once_for_test(0)` actually skips the next scan. If the
200 ms anchor has expired by then, the timer thread will execute the anchor and
then wait indefinitely on the empty heap, leaving the late task in the bucket.
##########
test/bthread_timer_thread_unittest.cpp:
##########
@@ -293,6 +298,207 @@ TEST(TimerThreadTest, schedule_and_unschedule_in_task) {
static void noop_routine(void*) {}
+void count_routine(void* arg) {
+ static_cast<std::atomic<int>*>(arg)->fetch_add(1,
+ std::memory_order_release);
+}
+
+class TimerThreadStopGuard {
+public:
+ explicit TimerThreadStopGuard(bthread::TimerThread* timer_thread)
+ : _timer_thread(timer_thread) {}
+
+ ~TimerThreadStopGuard() {
+ _timer_thread->stop_and_join();
+ }
+
+private:
+ bthread::TimerThread* _timer_thread;
+};
+
+class TimerWaitGate {
+public:
+ void arrive() {
+ std::unique_lock<std::mutex> lock(_mutex);
+ const int arrival = ++_arrivals;
+ _cv.notify_all();
+ if (arrival > 2) {
+ return;
+ }
+ _cv.wait(lock, [this, arrival] { return _released >= arrival; });
+ }
+
+ bool wait_for_arrivals(int target) {
+ std::unique_lock<std::mutex> lock(_mutex);
+ return _cv.wait_for(lock, std::chrono::seconds(1), [this, target] {
+ return _arrivals >= target;
+ });
+ }
+
+ void release(int arrival) {
+ std::lock_guard<std::mutex> lock(_mutex);
+ _released = std::max(_released, arrival);
+ _cv.notify_all();
+ }
+
+ void release_all() { release(std::numeric_limits<int>::max()); }
+
+ ~TimerWaitGate() { release_all(); }
+
+private:
+ std::mutex _mutex;
+ std::condition_variable _cv;
+ int _arrivals = 0;
+ int _released = 0;
+};
+
+void block_before_timer_wait(void* arg) {
+ static_cast<TimerWaitGate*>(arg)->arrive();
+}
+
+class ScopedTimerWaitHook {
+public:
+ ScopedTimerWaitHook(bthread::TimerThread* timer_thread,
+ TimerWaitGate* gate)
+ : _timer_thread(timer_thread) {
+ _timer_thread->_before_wait_hook = block_before_timer_wait;
+ _timer_thread->_before_wait_hook_arg = gate;
+ }
+
+ ~ScopedTimerWaitHook() {
+ _timer_thread->_before_wait_hook = nullptr;
+ _timer_thread->_before_wait_hook_arg = nullptr;
+ }
+
+private:
+ bthread::TimerThread* _timer_thread;
+};
+
+class TimerThreadHookStopGuard {
+public:
+ TimerThreadHookStopGuard(bthread::TimerThread* timer_thread,
+ TimerWaitGate* gate)
+ : _timer_thread(timer_thread), _gate(gate) {}
+
+ ~TimerThreadHookStopGuard() {
+ _gate->release_all();
+ _timer_thread->stop_and_join();
+ }
+
+private:
+ bthread::TimerThread* _timer_thread;
+ TimerWaitGate* _gate;
+};
+
+TEST(TimerThreadTest, sparse_buckets_execute_tasks) {
+ bthread::TimerThread timer_thread;
+ bthread::TimerThreadOptions options;
+ options.num_buckets = 1024;
+ ASSERT_EQ(0, timer_thread.start(&options));
+
+ std::atomic<int> completed(0);
+ TimerThreadStopGuard stop_timer(&timer_thread);
+ const int kTasks = 64;
+ for (int i = 0; i < kTasks; ++i) {
+ ASSERT_NE(bthread::TimerThread::INVALID_TASK_ID,
+ timer_thread.schedule(count_routine, &completed,
+ butil::microseconds_from_now(1)));
+ for (int retry = 0;
+ retry < 1000 && completed.load(std::memory_order_acquire) <= i;
+ ++retry) {
+ bthread_usleep(1000);
+ }
+ ASSERT_EQ(i + 1, completed.load(std::memory_order_acquire));
+ }
+}
+
+TEST(TimerThreadTest, later_empty_bucket_publication_survives_stale_hint) {
+ bthread::TimerThread timer_thread;
+ bthread::TimerThreadOptions options;
+ options.num_buckets = 1;
+ std::atomic<int> completed(0);
+ TimerWaitGate gate;
+ ScopedTimerWaitHook wait_hook(&timer_thread, &gate);
+ // Construct this last: its destructor releases the hook gate and joins
+ // the timer before the hook or gate can be destroyed.
+ TimerThreadHookStopGuard stop_timer(&timer_thread, &gate);
+ ASSERT_EQ(0, timer_thread.start(&options));
+
+ // Stop the timer at its first empty wait. After it is released, scheduling
+ // the anchor wakes it and moves the anchor into the private heap.
+ ASSERT_TRUE(gate.wait_for_arrivals(1));
+ gate.release(1);
+ ASSERT_NE(bthread::TimerThread::INVALID_TASK_ID,
+ timer_thread.schedule(count_routine, &completed,
+ butil::milliseconds_from_now(200)));
+
+ // The second gate is after the timer has scanned the empty bucket and
+ // selected the anchor as its heap deadline. The later task therefore does
+ // not change _nearest_run_time. It must still publish a wake sequence,
+ // otherwise this scan-to-wait window can lose the bucket publication.
+ ASSERT_TRUE(gate.wait_for_arrivals(2));
+ int signals_before;
+ {
+ BAIDU_SCOPED_LOCK(timer_thread._mutex);
+ signals_before = timer_thread._nsignals;
+ }
+ ASSERT_NE(bthread::TimerThread::INVALID_TASK_ID,
+ timer_thread.schedule(count_routine, &completed,
+ butil::milliseconds_from_now(400)));
+ {
+ BAIDU_SCOPED_LOCK(timer_thread._mutex);
+ EXPECT_EQ(signals_before + 1, timer_thread._nsignals);
+ }
+ // Model a legal stale false from the atomic fast-path load. The task stays
+ // linked in the bucket, and the publication protocol must ensure a later
+ // scan consumes it instead of leaving the timer asleep indefinitely.
+ timer_thread.force_empty_bucket_hint_once_for_test(0);
+ gate.release(2);
+
+ ASSERT_TRUE(WaitUntil([&completed] {
+ return completed.load(std::memory_order_acquire) == 2;
+ }));
+}
+
+// All producers use one bucket so Bucket::schedule() overlaps the timer
+// thread's consume_tasks(). This is primarily a TSAN regression for the
+// bucket-head publication race; the completion count also keeps it a normal
+// concurrent scheduling test.
+TEST(TimerThreadTest, concurrent_schedule_single_bucket) {
+ bthread::TimerThread timer_thread;
+ bthread::TimerThreadOptions options;
+ options.num_buckets = 1;
+ ASSERT_EQ(0, timer_thread.start(&options));
+
+ const int kProducers = 4;
+ const int kTasksPerProducer = 100000;
+ std::atomic<bool> start(false);
+ std::atomic<int> scheduled(0);
+ std::vector<std::thread> producers;
+ producers.reserve(kProducers);
+ for (int i = 0; i < kProducers; ++i) {
+ producers.emplace_back([&] {
+ while (!start.load(std::memory_order_acquire)) {
+ }
+ for (int j = 0; j < kTasksPerProducer; ++j) {
+ if (timer_thread.schedule(noop_routine, nullptr,
+ butil::microseconds_from_now(1)) !=
+ bthread::TimerThread::INVALID_TASK_ID) {
+ scheduled.fetch_add(1, std::memory_order_relaxed);
+ }
+ }
+ });
+ }
+ start.store(true, std::memory_order_release);
+ for (auto& producer : producers) {
+ producer.join();
+ }
+
+ EXPECT_EQ(kProducers * kTasksPerProducer,
+ scheduled.load(std::memory_order_relaxed));
+ timer_thread.stop_and_join();
Review Comment:
`scheduled` only counts successful enqueues. The assertion will pass even if
the consumer has not yet taken an entire batch of tasks, and the subsequent
`stop_and_join()` will prevent the remaining tasks from being returned to the
resource pool.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: [email protected]
For queries about this service, please contact Infrastructure at:
[email protected]
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]