首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >设置std::threads的线程亲和性

设置std::threads的线程亲和性
EN

Stack Overflow用户
提问于 2019-06-07 08:21:54
回答 1查看 895关注 0票数 2

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

我使用线程native_handle成员函数来获取提供给SetThreadAffinityMask函数的线程句柄。但是,这样做会导致SetThreadAffinityMask函数返回0,表示设置线程关联失败。

代码语言:javascript
复制
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

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-06-07 09:07:47

您的问题是将threads初始设置为包含numCores默认初始化的条目。之后,您的新线程(read: real)被推送到向量上,但是在设置亲和性时,您永远不会索引到它们。取而代之的是使用i进行索引,它只会在真正的线程之前命中未真正运行线程的向量中的对象。

一个实际值得运行的修正版本出现在下面:

代码语言:javascript
复制
#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();
}
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56486588

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档