正确使用SetThreadAffinityMask [英] Proper Usage of SetThreadAffinityMask

查看:1459
本文介绍了正确使用SetThreadAffinityMask的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有12个内核,正在运行12个线程.我想将1个线程绑定到每个内核.这就是我在每个线程开始时所说的.

There are 12 cores, and 12 threads running..I want to bind 1 thread to each core. this is what I call at the beginning of each thread.

int core=12;
SetThreadAffinityMask(GetCurrentThread(),(1<<core)-1);

这就是我所拥有的...我不知道这是否是调用它的正确方法.我不确定我是否了解第二个参数的工作原理.

This is what I have...I don't know if this would be the proper way to call it. I'm not sure if i'm understanding how the 2nd parameter works..

我还需要调用SetProcessaffinitymask吗?

Do i also need to call SetProcessaffinitymask as well?

推荐答案

SetThreadAffinityMask()的第二个参数是位向量.每一位对应一个逻辑处理器:CPU内核或超线程.如果第二个参数中的某个位设置为1,则允许该线程在相应的内核上运行.

The second parameter to SetThreadAffinityMask() is a bit vector. Each bit corresponds to a logical processor: a CPU core or a hyper-thread. If a bit in the second parameter is set to 1, the thread is allowed to run on the corresponding core.

对于等于12的core,您的掩码(1<<core)-1包含0..11位,因此每个线程都可以在12个内核中的任何一个上运行.大概您想将每个线程设置为在专用内核上运行.为此,您需要每个线程在0到11之间有一个唯一的数字,并仅设置亲和力掩码的相应位.提示:您可以使用InterlockedIncrement()来获取唯一编号.另外,如果您的线程全部在一个循环中启动,则唯一编号是已知的(这是循环行程计数),您可以使用它,例如传递给每个线程作为参数,或在同一循环中为新线程设置亲和力.

For core equal to 12, your mask (1<<core)-1 contains 0..11 bits set, so every thread is allowed to run on any of the 12 cores. Presumably you wanted to set each thread to run on a dedicated core. For this, you need each thread to have a unique number between 0 and 11, and set only the corresponding bit of the affinity mask. Hint: you may use InterlockedIncrement() to get the unique number. Alternatively, if your threads are all started in a loop, the unique number is already known (it's the loop trip count) and you may use it, e.g. pass to each thread as an argument, or set affinity for new threads in that same loop.

请注意大卫·赫弗南(David Heffernan)的回答:除非您知道如何善用亲和力,否则最好不要玩亲和力.除了David提到的原因之外,我还将在具有不同数量的套接字,内核和超线程的计算机之间增加应用程序的可移植性.

And please, pay attention to the caution in David Heffernan's answer: unless you know how to use affinity for good, you better do not play with affinity. In addition to the reasons David already mentioned, I will add application portability across computers having different number of sockets, cores, and hyper-threads.

这篇关于正确使用SetThreadAffinityMask的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆