Skip to content

Commit

Permalink
thread: optimize maybe_yield
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
travisdowns authored and avikivity committed Dec 11, 2024
1 parent b93bbc8 commit 2bba120
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 13 deletions.
10 changes: 8 additions & 2 deletions include/seastar/core/thread.hh
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
11 changes: 0 additions & 11 deletions src/core/thread.cc
Original file line number Diff line number Diff line change
Expand Up @@ -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

0 comments on commit 2bba120

Please sign in to comment.