简体   繁体   English

设置std :: threads的线程亲和力

[英]Setting Thread Affinity of std::threads

I am trying to figure out how to set the thread affinity of std::thread or boost::thread using the win32 API. 我试图弄清楚如何使用win32 API设置std :: thread或boost :: thread的线程亲和力。 I want to use the SetThreadAffinityMask function to pin each thread to a particular core in my machine. 我想使用SetThreadAffinityMask函数将每个线程固定到计算机中的特定内核。

I used the thread native_handle member function to obtain the thread handle that is provided to the SetThreadAffinityMask function. 我使用了线程native_handle成员函数来获取提供给SetThreadAffinityMask函数的线程句柄。 However, doing this results in the SetThreadAffinityMask function returning 0, indicating a failure to set thread affinity. 但是,执行此操作将导致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();
}

Original Thread Affinity Mask: 0 原始线程亲和力面罩:0

Original Thread Affinity Mask: 0 原始线程亲和力面罩:0

Original Thread Affinity Mask: 0 原始线程亲和力面罩:0

Original Thread Affinity Mask: 0 原始线程亲和力面罩:0

Original Thread Affinity Mask: 0 原始线程亲和力面罩:0

Original Thread Affinity Mask: 0 原始线程亲和力面罩:0

Original Thread Affinity Mask: 0 原始线程亲和力面罩:0

...etc ...等等

Your problem is the intial setup of threads to contain numCores default-initialized entries. 您的问题是包含numCores默认初始化项的threads的初始设置。 Your new (read: real) threads are pushed on the vector afterward, but you never index to them when setting affinity. 新线程(已读:实数)随后被推到向量上,但是在设置亲和力时,您永远不会索引到它们。 Instead you index using i , which just hits the objects in the vector that aren't really running threads, prior to your real threads. 取而代之的是,您使用i索引,它会在实际线程之前命中向量中不是真正在运行线程的对象。

A corrected version that's actually run-worthy appears below: 下面是实际值得运行的更正版本:

#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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM