gpt4 book ai didi

c++ - std::this_thread::yield 只是一个提示会不会有问题?

转载 作者:行者123 更新时间:2023-11-30 00:36:59 40 4
gpt4 key购买 nike

同事和我讨论了一个假设的问题,当一个人想用 std::atomic_flag 实现自旋锁互斥锁,但也实现自旋锁不是 while(true) 而是作为

while(true)
{
cnt=0;
while (cnt<yieldAfterTries)
{
//try to get lock
cnt++;
}
std::this_thread::yield();

// if got lock do work and then break;
}

基本的想法是线程不能“长时间”阻塞其他线程,即使它具有实时优先级,因为它会在一段时间后放弃......但是当我看到std::yield 的规范我很惊讶这是一个建议,而不是强制性的。

Provides a hint to the implementation to reschedule the execution of threads, allowing other threads to run.

http://en.cppreference.com/w/cpp/thread/yield

那会不会有问题?

最佳答案

我编写的代码与您的非常相似,并测量了在高竞争条件下调用 yield 的影响。我发现以这种方式使用 yield 有利于整体系统吞吐量。

实际规范与您引用的在精神上没有什么不同,但这里是 30.3.2 [thread.thread.this] 第 2 段和第 3 段的确切规范:

void this_thread::yield() noexcept;

Effects: Offers the implementation the opportunity to reschedule.

Synchronization: None.

如果实现将 yield 实现为空操作(例如),这只会影响代码的性能而不影响正确性。即使没有 yield,失败的自旋锁最终也会被抢占。但它也更有可能不必要地占用 CPU,从而降低整体系统性能。

关于c++ - std::this_thread::yield 只是一个提示会不会有问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14402328/

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