正确可以使用的SetThreadAffinityMask

void SetCoreMask(short nMask)
{
    SYSTEM_INFO si;
    GetSystemInfo(&si);

    short nValue = 0x0001;
    for (int i=0; i<(si.dwNumberOfProcessors-1); ++i)
    {
        nValue = nValue << 1;
        nValue |= 0x0001;
    }

    if (nMask <= nValue)
        m_nAffinityMask = nMask;
}

bool AttachToCore()
{
    m_dwID = GetCurrentThreadId();
    HANDLE hThread, hThreadDup;
    hThread = GetCurrentThread();
    BOOL bSuccess = DuplicateHandle(GetCurrentProcess(), hThread,
        GetCurrentProcess(), &hThreadDup,
        0, FALSE,
        DUPLICATE_SAME_ACCESS);
    CloseHandle(hThread);

    if (!bSuccess)
        return FALSE;

    m_handle = hThreadDup;
    SetThreadAffinityMask(hThread, m_nAffinityMask);

    return TRUE;
}

 

然后再程序开始的地方(比较靠前的地方)加入:

    SetCoreMask((short)m_CPUCoreNO);
    if(!AttachToCore())
    {
        printf("指定的CPU核心%d有误,程序退出。",m_CPUCoreNO);

        //暂停窗口
        system("pause");

        return 0;
    }

 

 

你可能感兴趣的:(R3)