实施std::this_thread::yield
in the libstdc++ 库 https://github.com/gcc-mirror/gcc/blob/master/libstdc%2B%2B-v3/include/std/thread#L370看起来像这样:
/// yield
inline void
yield() noexcept
{
#ifdef _GLIBCXX_USE_SCHED_YIELD
__gthread_yield();
#endif
}
符号__gthread_yield
定义为在 gcc 中的 gthr-posix.h 中 https://github.com/gcc-mirror/gcc/blob/master/libgcc/gthr-posix.h#L691我们需要以下内容:
# 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) ();
}
所以基本上在 gcc 调用中std::this_thread::yield
calls sched_yield
if _GLIBCXX_USE_SCHED_YIELD
被定义为。你可以找到如果_GLIBCXX_USE_SCHED_YIELD
定义于#include <bits/c++config.h>
,但在 linux x86 或 x86_64 上它很可能已定义。所以std::this_thread::yield
应该打电话sched_yield
使用 gcc GNU 编译器集合和 libstdc++ GNU C++ 库实现。
在“libc++”C++ 标准库中std::this_thread::yield
可以找到函数定义在 libcxx/线程中 https://github.com/llvm-mirror/libcxx/blob/master/include/thread#L410:
inline _LIBCPP_INLINE_VISIBILITY
void yield() _NOEXCEPT {__libcpp_thread_yield();}
符号__libcpp_thread_yield
定义于libcxx/threading_support https://github.com/llvm-mirror/libcxx/blob/master/include/__threading_support#L359:
void __libcpp_thread_yield()
{
sched_yield();
}
所以 clang 编译器(即使用 libc++ C++ 标准库的编译器)也调用sched_yield
on std::this_thread::yield
.
我只是想知道 std::this_thread::yield 在 linux 上是如何实现的,它与 sched_yield 有什么不同吗?
很可能在大多数 Linux 实现上都是相同的。
我看到一些自旋锁实现暗示 std::this_thread::yield 比 sched_yield 更轻量级,就线程放弃进程的时间而言,是真的吗?
在大多数 Linux 实现上它很可能是错误的。