[英]Setting Thread Affinity of std::threads
我試圖弄清楚如何使用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
...等等
您的問題是包含numCores
默認初始化項的threads
的初始設置。 新線程(已讀:實數)隨后被推到向量上,但是在設置親和力時,您永遠不會索引到它們。 取而代之的是,您使用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();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.