From 2bba1204dbb018ff1551d08fc80a951af918a37d Mon Sep 17 00:00:00 2001 From: Travis Downs Date: Wed, 11 Dec 2024 16:04:30 -0300 Subject: [PATCH] thread: optimize maybe_yield thread::maybe_yield, a static method, calls into thread_impl::maybe_yield which is a member function on the current thread context, which means we need to access the TLS etc, but this function is itself essentially static as it only calls needs_prempt(). This was probably different in the ancient past where there were thread-specific scheduling groups, etc. This method is performance sensitive as it is often called in loops, even tight loops as it is often difficult to call it less frequently in a tight loop which may have a large trip count. Therefore it is worth optimizing. So this change: - Have thread::maybe_yield just call needs_prempt() directly - Move maybe_yield and should_yield in to the header. This latter change doesn't change needed includes, so shouldn't impact compile time. The yield() function itself is still out-of-line. This provides a chance for the compile to hoist the TLS access boilerplate out of loops. --- include/seastar/core/thread.hh | 10 ++++++++-- src/core/thread.cc | 11 ----------- 2 files changed, 8 insertions(+), 13 deletions(-) diff --git a/include/seastar/core/thread.hh b/include/seastar/core/thread.hh index 85750afd0bd..14811fb6e4b 100644 --- a/include/seastar/core/thread.hh +++ b/include/seastar/core/thread.hh @@ -183,13 +183,19 @@ public: /// /// Useful where we cannot call yield() immediately because we /// Need to take some cleanup action first. - static bool should_yield(); + static bool should_yield() { + return need_preempt(); + } /// \brief Yield if this thread ought to call yield() now. /// /// Useful where a code does long running computation and does /// not want to hog cpu for more then its share - static void maybe_yield(); + static void maybe_yield() { + if (should_yield()) [[unlikely]] { + yield(); + } + } static bool running_in_thread() { return thread_impl::get() != nullptr; diff --git a/src/core/thread.cc b/src/core/thread.cc index c5d81db2991..228cea2c66f 100644 --- a/src/core/thread.cc +++ b/src/core/thread.cc @@ -354,17 +354,6 @@ void thread::yield() { thread_impl::get()->yield(); } -bool thread::should_yield() { - return thread_impl::get()->should_yield(); -} - -void thread::maybe_yield() { - auto tctx = thread_impl::get(); - if (tctx->should_yield()) { - tctx->yield(); - } -} - } /// \endcond