gpt4 book ai didi

multithreading - 与 Windows、MSVC 和 OpenMP 的线程关联

转载 作者:行者123 更新时间:2023-12-04 04:32:50 25 4
gpt4 key购买 nike

我想将代码中的线程绑定(bind)到每个物理内核。
使用 GCC,我已经使用 sched_setaffinity 成功完成了这项工作。所以我不再需要设置 export OMP_PROC_BIND=true .我想在 Windows 中使用 MSVC 做同样的事情。 Windows 和 Linux 使用不同的线程拓扑。 Linux 分散线程,而 Windows 使用紧凑形式。换句话说,在具有四个内核和八个超线程的 Linux 中,我只需要将线程绑定(bind)到前四个处理单元。在 Windows 中,我将它们设置为每个其他处理单元。

我已经使用 SetProcessAffinityMask 成功完成了这项工作。 .当我右键单击进程并单击“设置亲和性”时,我可以从 Windows 任务管理器中看到所有其他 CPU 已设置(我的八个超线程系统上的 0、2、4、6)。问题是我的代码运行时效率不稳定。有时它几乎是恒定的,但大多数时候它有很大的变化。我将优先级更改为高,但没有区别。在Linux中效率是稳定的。也许 Windows 仍在迁移线程?我还需要做些什么来绑定(bind) Windows 中的线程吗?

这是我正在使用的代码

#ifdef _WIN32   
HANDLE process;
DWORD_PTR processAffinityMask = 0;
//Windows uses a compact thread topology. Set mask to every other thread
for(int i=0; i<ncores; i++) processAffinityMask |= 1<<(2*i);
//processAffinityMask = 0x55;
process = GetCurrentProcess();
SetProcessAffinityMask(process, processAffinityMask);
#else
cpu_set_t mask;
CPU_ZERO(&mask);
for(int i=0; i<ncores; i++) CPU_SET(i, &mask);
sched_setaffinity(0, sizeof(mask), &mask);
#endif

编辑:这是我现在使用的代码,在 Linux 和 Windows 上似乎很稳定
    #ifdef _WIN32   
HANDLE process;
DWORD_PTR processAffinityMask;
//Windows uses a compact thread topology. Set mask to every other thread
for(int i=0; i<ncores; i++) processAffinityMask |= 1<<(2*i);
process = GetCurrentProcess();
SetProcessAffinityMask(process, processAffinityMask);
#pragma omp parallel
{
HANDLE thread = GetCurrentThread();
DWORD_PTR threadAffinityMask = 1<<(2*omp_get_thread_num());
SetThreadAffinityMask(thread, threadAffinityMask);
}
#else
cpu_set_t mask;
CPU_ZERO(&mask);
for(int i=0; i<ncores; i++) CPU_SET(i, &mask);
sched_setaffinity(0, sizeof(mask), &mask);
#pragma omp parallel
{
cpu_set_t mask;
CPU_ZERO(&mask);
CPU_SET(omp_get_thread_num(),&mask);
pthread_setaffinity_np(pthread_self(), sizeof(mask), &mask);
}
#endif

最佳答案

您应该使用 SetThreadAffinityMask函数(见 MSDN reference)。您正在设置 流程 的面具。

您可以获得thread ID在 OpenMP 中使用以下代码:

int tid = omp_get_thread_num();

然而,上面的代码提供了 OpenMP 的内部 thread ID ,而不是系统 thread ID .本文解释了有关该主题的更多信息:

http://msdn.microsoft.com/en-us/magazine/cc163717.aspx

如果您需要明确使用这些 trheads - 使用 显式 affinity type如本英特尔文档中所述:

https://software.intel.com/sites/products/documentation/studio/composer/en-us/2011Update/compiler_c/optaps/common/optaps_openmp_thread_affinity.htm

关于multithreading - 与 Windows、MSVC 和 OpenMP 的线程关联,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24862488/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com