实现自旋锁与 Win32 临界区

发布于 2025-01-14 21:22:24 字数 1026 浏览 0 评论 0原文

我正在尝试优化 Win32 的 CRITICAL_SECTION 以实现更“复杂”的同步原语,其中我不需要关键部分的重入功能。到目前为止,这是我的自旋锁:

class MSpinLock
{
    volatile LONG X;
public:
    
    void Enter()
    {
        while (1)
        {
            const LONG ret = ::InterlockedExchange(&X, 1);
            if (X == 1 && ret == 0) break;

            MBOOL shouldsleep = 1;
            for (int iter=0; iter<1024; iter++)
            {
                _mm_pause();
                if (X == 0) { shouldsleep = 0; break; };
            };
            if (shouldsleep) ::SwitchToThread();
        };
    };

    //void Exit() { ::InterlockedExchange(&X, 0); };
    void Exit() { X = 0; };
};

第一个问题是这样的 Exit 实现是否足够?

主要是我开始通过分配多个线程来将它与临界区进行比较,这些线程执行如下操作:

for (int i=0; i<10000000; i++)
{
    TheLock.Enter();
    DummyVariable++;
    TheLock.Exit();
};

然后只是等待线程。这不完全是科学测试,但目前显然已经达到了目的 - 只需一个线程,线程完成速度比使用关键部分快 3 倍。但一旦线程增多,情况就会变得更糟。显然,当存在并发线程时,算法开始在循环中的某个地方花费太多时间,或者公平性可能太差了。有什么想法如何优化这个吗?

I'm trying to optimize Win32's CRITICAL_SECTION for more "complex" synchronization primitives, where I don't need the reentrance feature of the critical section. So here's my spin lock so far:

class MSpinLock
{
    volatile LONG X;
public:
    
    void Enter()
    {
        while (1)
        {
            const LONG ret = ::InterlockedExchange(&X, 1);
            if (X == 1 && ret == 0) break;

            MBOOL shouldsleep = 1;
            for (int iter=0; iter<1024; iter++)
            {
                _mm_pause();
                if (X == 0) { shouldsleep = 0; break; };
            };
            if (shouldsleep) ::SwitchToThread();
        };
    };

    //void Exit() { ::InterlockedExchange(&X, 0); };
    void Exit() { X = 0; };
};

The first question is whether the Exit implementation is sufficient like this?

And mainly I started comparing it to critical sections by allocating multiple threads which do something like this:

for (int i=0; i<10000000; i++)
{
    TheLock.Enter();
    DummyVariable++;
    TheLock.Exit();
};

Then just waiting for the threads. It's not exactly scientific test, but does the trick for now apparently - with just a single thread, the threads finish 3x faster compare to using the critical section. But once there are more threads it gets way worse. So apparently when there are concurrent threads, the algorithm starts spending too much time somewhere in the loop, or perhaps the fairness is just too bad. Any ideas how to optimize this?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文