multithreading - 使用 openMP 进行多核处理与多线程

标签 multithreading multiprocessing openmp multicore

这个问题听起来很基础,但我找不到具体的答案。所以现在假设我们有一个像 corei5 680 这样的多核处理器(2 个物理内核和 HT 为操作系统启用了 4 个可用内核)。 我的问题是 openMP 究竟在哪里适合图片? 1 - 当我们说使用 openMP 的多线程时,它会自动利用所有可用内核(在本例中为 4 个虚拟内核)并根据可用的 CPU 周期执行线程吗? 2 - openmp 是否可以控制如何使用物理/虚拟内核?或者它是抽象的并提供像 java 这样的多线程环境?

如果这听起来很基础,请原谅,但我试图在网上找到答案,但没有找到令人满意的答案。

谢谢

最佳答案

这在一定程度上取决于您正在考虑的 OpenMP 版本/功能,因为我相信更高版本可能会为您提供更多功能,但原始库是围绕 for 原语数据并行构建的。通常,OpenMP 和其他数据并行编程模型会尝试抽象出底层硬件,程序员将其计算声明为对数据的一系列操作,然后由 OMP 进行调度。

要回答您的第一个问题,操作系统调度程序将跨内核调度线程,OMP 调度程序将跨可用线程调度工作。

#pragma omp parallel for
for (i = 0; i < N; i++)
    a[i] = 2 * i;

OMP 调度程序将根据多种因素选择使用哪些内核(真实或 HT),包括它们的负载、分配给它的工作量以及您可能提供的任何提示。人们会期望上面的代码在所有可用的核心上运行(在你的例子中是 4 个)

您可以使用 schedule 关键字来控制调度程序如何分配工作。

schedule(type, chunk): This is useful if the work sharing construct is a do-loop or for-loop. The iteration(s) in the work sharing construct are assigned to threads according to the scheduling method defined by this clause. The three types of scheduling are:

static: Here, all the threads are allocated iterations before they execute the loop iterations. The iterations are divided among threads equally by default. However, specifying an integer for the parameter chunk will allocate chunk number of contiguous iterations to a particular thread.

dynamic: Here, some of the iterations are allocated to a smaller number of threads. Once a particular thread finishes its allocated iteration, it returns to get another one from the iterations that are left. The parameter chunk defines the number of contiguous iterations that are allocated to a thread at a time.

guided: A large chunk of contiguous iterations are allocated to each thread dynamically (as above). The chunk size decreases exponentially with each successive allocation to a minimum size specified in the parameter chunk

来自 Wikipedia

回答你的第二个问题。您还可以使用 num_threads 属性来指定要使用的线程数。在示例中的 #pragma omp parallel for 上方添加以下内容会将 OMP 限制为三个线程,无论是否有更多线程可用。

#pragma omp parallel num_threads(3)
#pragma omp for
for (i = 0; i < N; i++)
    a[i] = 2 * i;

还可以在某种程度上控制多处理器(多个插槽)系统中不同处理器之间的工作调度方式。 OpenMP and NUMA relation?

您可能还会发现以下指南很有用,Guide into OpenMP: Easy multithreading programming for C++ .

关于multithreading - 使用 openMP 进行多核处理与多线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40746514/

相关文章:

c# - IOException 被 ReaderWriteLockSlim 抛出?

python - 如何在 "background"中运行部分脚本(单个函数)?

opencv - OpenMP边缘检测过滤器并行性:需要更长的时间

c++ - 嵌套循环中的 OpenMP 数组索引

c++ - 如何同时填充 std::unordered_map?

python - 如何继续关闭子线程以关闭标准输入文件描述符?

C# 多线程从主数组更新/读取

c++ - 为什么 pthread_attr_setstacksize() 对我不起作用?

c# - Windows 服务器/数据中心 : set CPU affinity with > 64 cores

python - 在进程对象之间共享 SciPy 稀疏数组