SetThreadAffinityMask

#include   
#include   
#include 

#define ThreadCount 8
#define USE__beginthreadex
#ifndef USE__beginthreadex
unsigned __stdcall func(void * pParam)
{
    while (1) {
        //Sleep(0);
    }
    return 0;
}
#else
DWORD WINAPI func(LPVOID pvoid)
{
    while (1) {
        Sleep(0);
    }
    return 0;
}
#endif
int main()
{
    SYSTEM_INFO SystemInfo;
    GetSystemInfo(&SystemInfo);
    DWORD CPU_num = SystemInfo.dwNumberOfProcessors;
    printf("cpu_num = %d\n", CPU_num);

    HANDLE threads[ThreadCount];
    unsigned threadID[ThreadCount];     
    int i;
    for (i = 0; i < ThreadCount; i++)
    {
#ifdef USE__beginthreadex
        threads[i] = (HANDLE)_beginthreadex(NULL, 0, func,NULL, 0, &threadID[i]);
#else
        threads[i] = CreateThread(NULL, 0, func, NULL, 0, NULL);
#endif
        SetThreadAffinityMask(threads[i], 1 << i);
        if (threads[i] == NULL)
        {
            OutputDebugString(_T("CreateThread Error!\n"));
            exit(1);
        }
    }
    getchar();
    return 0;
}

//指定线程到第1个CPU上,则mask=0x01 (00000001)
//指定线程到第2个CPU上,则mask=0x02 (00000010)
//指定线程到第3个CPU上,则mask=0x04 (00000100)
//...

好像并没有什么用,windows操作系统会自动调度线程将其分配到空闲的核心上去。

你可能感兴趣的:(C/C++)