I am just wondering how std::this_thread::yield is implemented on linux and is it any different from sched_yield? I have seen some spinlock implementations that imply std::this_thread::yield being something more lightweight that sched_yield in terms of for how long the threads abandons the process, is it true?
The implementation of std::this_thread::yield in the libstdc++ library looks like this:
/// yield
inline void
yield() noexcept
{
#ifdef _GLIBCXX_USE_SCHED_YIELD
__gthread_yield();
#endif
}
The symbol __gthread_yield is defined by in gcc in gthr-posix.h from which we would need the following:
# define __gthrw2(name,name2,type) \
static __typeof(type) name \
__attribute__ ((__weakref__(#name2), __copy__ (type))); \
__gthrw_pragma(weak type)
# define __gthrw_(name) __gthrw_ ## name
...
/* Typically, __gthrw_foo is a weak reference to symbol foo. */
#define __gthrw(name) __gthrw2(__gthrw_ ## name,name,name)
...
__gthrw(sched_yield)
...
static inline int
__gthread_yield (void)
{
return __gthrw_(sched_yield) ();
}
So basically in gcc calling std::this_thread::yield calls sched_yield if _GLIBCXX_USE_SCHED_YIELD is defined. You can find if _GLIBCXX_USE_SCHED_YIELD is defined in #include <bits/c++config.h>, but on linux x86 or x86_64 it most probably is defined. So std::this_thread::yield should just call sched_yield on a implementation using gcc GNU Compiler Collection and libstdc++ the GNU C++ Library.
In "libc++" C++ Standard Library the std::this_thread::yield function definition can be found in libcxx/thread:
inline _LIBCPP_INLINE_VISIBILITY
void yield() _NOEXCEPT {__libcpp_thread_yield();}
The symbol __libcpp_thread_yield is defined in libcxx/threading_support:
void __libcpp_thread_yield()
{
sched_yield();
}
So clang compiler (ie. a compiler that uses libc++ C++ standard library) also calls sched_yield on std::this_thread::yield.
I am just wondering how std::this_thread::yield is implemented on linux and is it any different from sched_yield?
Most probably it's the same on most linux implementations.
I have seen some spinlock implementations that imply std::this_thread::yield being something more lightweight that sched_yield in terms of for how long the threads abandons the process, is it true?
It is most probably false on most linux implementations.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With