gpt4 book ai didi

c++ - 如何使用 C++11 为 x86(-64) 安全地编写测试和测试并设置 (TATAS) 自旋锁?

转载 作者:行者123 更新时间:2023-11-28 06:21:43 26 4
gpt4 key购买 nike

我目前正在研究 Spinlock 类并尝试使其尽可能合理,主要基于此处的建议:https://software.intel.com/en-us/articles/implementing-scalable-atomic-locks-for-multi-core-intel-em64t-and-ia32-architectures

正在进行的工作看起来像这样:

class Spinlock
{
public:
Spinlock() : m_lock(false) {}

void lock()
{
// heavy test here for the usual uncontested case
bool exp = false;
if (!m_lock.compare_exchange_weak(exp, true, std::memory_order_acquire))
{
int failCount = 0;
for (;;)
{
// processor spin loop hint
_mm_pause();

// spin on mov instead of lock instruction
if (!m_lock.load(std::memory_order_relaxed))
{
// heavy test now that we suspect success
exp = false;
if (m_lock.compare_exchange_weak(exp, true, std::memory_order_acquire))
{
return;
}
}

// backoff (potentially make exponential later)
if (++failCount == SOME_VALUE)
{
// Yield somehow.
failCount = 0;
}
}
}
}

void unlock()
{
m_lock.store(false, std::memory_order_release);
}

std::atomic_bool m_lock;
};

然而,似乎在理论上轻松读取可以允许生成的代码执行意想不到的事情,例如创建死锁:http://joeduffyblog.com/2009/02/23/the-magical-dueling-deadlocking-spin-locks/

此代码不应像链接示例那样死锁,因为外部获取应防止松弛负载漂移,但我并没有真正掌握可能存在的所有代码转换。我需要什么内存顺序和/或栅栏来保证这段代码的安全而不损失性能?由于周围的内存顺序过于宽松,退避实现是否可能比预期更频繁或更不频繁地发生(> 几个循环)?

在相关说明中,为什么网络上的自旋锁示例使用自旋锁的获取/释放内存顺序而不是顺序一致?我发现一条评论说允许自旋锁释放跨越后来的自旋锁获取可能会导致问题:http://preshing.com/20120913/acquire-and-release-semantics/#IDComment721195810

最佳答案

This code shouldn't deadlock in the same way as the linked example because the outer acquire should keep the relaxed load from drifting behind, but I don't really have a handle on all the code transformations that could exist.

获取操作保证后续读取不会在编译器和 CPU 获取操作之前重新排序。

What memory orders and/or fences do I need to keep this code safe without losing performance?

您在这里不需要任何额外的同步,您的代码会做正确的事情。

why are spinlock examples around the web using acquire/release memory order for spinlocks instead of sequentially consistent?

因为获取/释放语义足以实现互斥量。在某些架构上,顺序一致性操作比获取/释放更昂贵。

我不能推荐足够的观看 atomic<> Weapons: The C++ Memory Model and Modern Hardware ,它非常详细地介绍了这个主题。

关于c++ - 如何使用 C++11 为 x86(-64) 安全地编写测试和测试并设置 (TATAS) 自旋锁?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29202475/

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