我正在尝试弄清楚如何使用win32 API设置std::thread或boost::thread的线程亲和性。我想使用SetThreadAffinityMask函数将每个线程固定到我的机器中的特定内核。
我使用线程native_handle成员函数来获取提供给SetThreadAffinityMask函数的线程句柄。但是,这样做会导致SetThreadAffinityMask函数返回0,表示设置线程关联失败。
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
...etc
发布于 2019-06-07 09:07:47
您的问题是将threads初始设置为包含numCores默认初始化的条目。之后,您的新线程(read: real)被推送到向量上,但是在设置亲和性时,您永远不会索引到它们。取而代之的是使用i进行索引,它只会在真正的线程之前命中未真正运行线程的向量中的对象。
一个实际值得运行的修正版本出现在下面:
#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 << '\n';
}
}
for (auto& t : threads)
t.join();
}https://stackoverflow.com/questions/56486588
复制相似问题