gpt4 book ai didi

c++ - std::this_thread::yield 与 linux 上的 sched_yield 有什么不同吗?

转载 作者:行者123 更新时间:2023-12-02 09:50:52 29 4
gpt4 key购买 nike

我只是想知道 std::this_thread::yield 在 linux 上是如何实现的,它与 sched_yield 有什么不同吗?我看到一些自旋锁实现暗示 std::this_thread::yield 在线程放弃进程的时间方面比 sched_yield 更轻量级,这是真的吗?

最佳答案

执行std::this_thread::yieldlibstdc++ library看起来像这样:

    /// yield
inline void
yield() noexcept
{
#ifdef _GLIBCXX_USE_SCHED_YIELD
__gthread_yield();
#endif
}

符号__gthread_yieldin gcc in gthr-posix.h 定义从中我们需要以下内容:

# 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电话 sched_yield如果_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可以找到函数定义 in libcxx/thread :

inline _LIBCPP_INLINE_VISIBILITY
void yield() _NOEXCEPT {__libcpp_thread_yield();}

符号__libcpp_thread_yieldlibcxx/threading_support 中定义:

void __libcpp_thread_yield()
{
sched_yield();
}

因此 clang 编译器(即使用 libc++ C++ 标准库的编译器)也调用 sched_yieldstd::this_thread::yield .

I am just wondering how std::this_thread::yield is implemented on linux and is it any different from sched_yield?

很可能在大多数 Linux 实现上都是一样的。

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?

在大多数 Linux 实现上它很可能是错误的。

关于c++ - std::this_thread::yield 与 linux 上的 sched_yield 有什么不同吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59600135/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com