关于C#:设置std :: threads的线程亲和力

Setting Thread Affinity of std::threads

我试图弄清楚如何使用win32 API设置std :: thread或boost :: thread的线程亲和力。我想使用SetThreadAffinityMask函数将每个线程固定到计算机中的特定内核。

我使用了线程native_handle成员函数来获取提供给SetThreadAffinityMask函数的线程句柄。但是,执行此操作将导致SetThreadAffinityMask函数返回0,表示无法设置线程相似性。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
unsigned numCores = std::thread::hardware_concurrency();
std::vector<std::thread> threads(numCores);

for (int i = 0; i < numCores; i++)
{
    threads.push_back(std::thread(workLoad, i));
    cout <<"Original Thread Affinity Mask:" << SetThreadAffinityMask(threads[i].native_handle() , 1 << i) << endl;

}

for (thread& t : threads)
{
    if (t.joinable())
        t.join();
}

原始线程亲和力掩码:0

原始线程亲和力掩码:0

原始线程亲和力掩码:0

原始线程亲和力掩码:0

原始线程亲和力掩码:0

原始线程亲和力掩码:0

原始线程亲和力掩码:0

...等


您的问题是threads的初始设置以包含numCores默认初始化的条目。您的新(已读:实数)线程随后被推到向量上,但是在设置亲和力时,您永远不会索引到它们。取而代之的是,您使用i进行索引,该索引会在实际线程之前命中向量中不是真正在运行线程的对象。

实际可运行的更正版本显示在下面:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#include <iostream>
#include <vector>
#include <thread>
#include <chrono>

#include <windows.h>

void proc(void)
{
    using namespace std::chrono_literals;
    std::this_thread::sleep_for(5s);
}

int main()
{
    std::vector<std::thread> threads;
    for (unsigned int i = 0; i < std::thread::hardware_concurrency(); ++i)
    {
        threads.emplace_back(proc);
        DWORD_PTR dw = SetThreadAffinityMask(threads.back().native_handle(), DWORD_PTR(1) << i);
        if (dw == 0)
        {
            DWORD dwErr = GetLastError();
            std::cerr <<"SetThreadAffinityMask failed, GLE=" << dwErr << '\
'
;
        }
    }

    for (auto& t : threads)
        t.join();
}