c++ - 没有 mutex.h 的 VC++ 中的自旋锁同步

标签 c++ multithreading winapi visual-c++ synchronization

我有点迷路了。我相信我在这里拥有的绝对是线程安全的,但我不确定。我需要一个非常快速的自旋锁机制,用于优化线程锁定和释放的更复杂锁的一小部分(我需要制作一个更大的锁,始终按照线程阻塞的顺序释放线程 - mutex/EnterCriticalSection 不会发生这种情况) .然而 - 当涉及到尽可能实现最小和最快的锁时,我不确定该怎么做。

class SpinGate
{
private:
    volatile LONGLONG key = 0;
    volatile LONGLONG gate = 1;
public:
    void EnterGate();
    void ExitGate();
};

void SpinGate::EnterGate()
{
    LONGLONG myKey = InterlockedAdd64(&key, 1);

    while (myKey != gate) {}
}

void SpinGate::ExitGate()
{
    InterlockedAdd64(&gate, 1);
}

认为我构建的这个东西将确保,即使 1,000,000,000 个线程同时尝试获取 key ,它们都将获得不同的 key ,因此被迫自旋直到他们的 key 出现。但是当谈到 C++ 时,在没有标准库对象的情况下实现内存安全读写的机制有点超出了我的知识范围。

我很好奇像“interlockedadd64”这样的函数究竟是如何同时执行两个操作的,一个递增,然后一个读取,同时阻塞其他线程。以及这是否始终线程安全。

最佳答案

I think this thing I've constructed will ensure that, even if 1,000,000,000 threads try to get a key at the exact same time, they will all get a different key and hence be forced to spin until their key comes up.

没有。 C++ volatile 关键字不提供任何线程间保证。

I'm curious how exactly a function like "interlockedadd64" performs two operations at once, an increment and then a read, while blocking other threads. And whether or not this is always threadsafe.

它不会阻塞其他线程。在现代 CPU 上,它只是在原子操作期间锁定缓存行,这样其他核心就无法在读取和写入之间访问该内存位置。

关于c++ - 没有 mutex.h 的 VC++ 中的自旋锁同步,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34081182/

相关文章:

c++ - 从存储过程中的临时表中选择

c++ - 如何使 libpcap/pcap_loop 成为非阻塞的?

multithreading - 上下文在 sleep /等待线程上切换

java - CountDownLatch 是否受到虚假唤醒的影响?

C++ Win32 如何将此函数放在单独的 cpp 文件中?

c++ - 在 (unordered_)set 中修改 shared_ptr 是否安全?

c++ - 在 C++ 中为多维特征矩阵赋值?

c++ - 避免复制返回当前对象

c++ - 在 Windows 1809 中操作系统/可见剪切区域

c - Win32 C 运行时库中的文件元数据