首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >什么是Linux和Mac上的Windows .NET (C++) SpinWait的等价物?

什么是Linux和Mac上的Windows .NET (C++) SpinWait的等价物?
EN

Stack Overflow用户
提问于 2015-07-06 20:03:35
回答 1查看 582关注 0票数 2

Windows .NET (C++)为超线程友好的忙碌等待提供了SpinWait,并提供了放弃/暂停指令。Linux和Mac OS X上的等效功能是什么?如果系统调用不可用,如何在用户空间中实现等效调用?

请参阅Windows Thread::SpinWait

有关旋转等待的性能问题的讨论,请参阅Long Duration Spin-wait Loops on Hyper-Threading Technology Enabled Intel Processors

EN

回答 1

Stack Overflow用户

发布于 2018-05-12 06:34:24

请参阅sameer_87https://www.codeproject.com/articles/184046/spin-lock-in-c

代码语言:javascript
复制
#include "SpinLock.h"
#include <iostream>

using namespace LockFree;
using namespace std;

void tSpinWait::Lock(tSpinLock &LockObj)
{
    m_iterations = 0;
    while(true)
    {
        // A thread alreading owning the lock shouldn't be allowed to wait to acquire the lock - reentrant safe
        if(LockObj.dest == GetCurrentThreadId())
            break;
        /*
          Spinning in a loop of interlockedxxx calls can reduce the available memory bandwidth and slow
          down the rest of the system. Interlocked calls are expensive in their use of the system memory
          bus. It is better to see if the 'dest' value is what it is expected and then retry interlockedxx.
        */
        if(InterlockedCompareExchange(&LockObj.dest, LockObj.exchange, LockObj.compare) == 0)
        {
            //assign CurrentThreadId to dest to make it re-entrant safe
            LockObj.dest = GetCurrentThreadId();
            // lock acquired 
            break;          
        }

        // spin wait to acquire 
        while(LockObj.dest != LockObj.compare)
        {
            if(HasThreasholdReached())
            {
                if(m_iterations + YIELD_ITERATION >= MAX_SLEEP_ITERATION)
                    Sleep(0);

                if(m_iterations >= YIELD_ITERATION && m_iterations < MAX_SLEEP_ITERATION)
                {
                    m_iterations = 0;
                    SwitchToThread();
                }
            }
            // Yield processor on multi-processor but if on single processor then give other thread the CPU
            m_iterations++;
            if(Helper::GetNumberOfProcessors() > 1) { YieldProcessor(/*no op*/); }
            else { SwitchToThread(); }              
        }               
    }
}
//

void tSpinWait::Unlock(tSpinLock &LockObj)
{
    if(LockObj.dest != GetCurrentThreadId())
        throw std::runtime_error("Unexpected thread-id in release");
    // lock released
    InterlockedCompareExchange(&LockObj.dest, LockObj.compare, GetCurrentThreadId());   
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/31245364

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档