我想知道是否有任何技术可以使用for循环在OpenMp中创建并行部分。
例如,我不想创建n个不同的#pragma omp节,而是使用n-iteration for-loop 创建它们,并为每个节创建一些参数。
#pragma omp parallel sections
{
#pragma omp section
{
/* Executes in thread 1 */
}
#pragma omp section
{
/* Executes in thread 2 */
}
#pragma omp section
{
/* Executes in thread n */
}
}
答案 0 :(得分:4)
使用明确的OpenMP任务:
#pragma omp parallel
{
// Let only one thread create all tasks
#pragma omp single nowait
{
for (int i = 0; i < num_tasks; i++)
#pragma omp task
{
// Code for task with parameters, based on i
}
}
// Let the threads process all tasks
#pragma omp taskwait
// Further parallel processing ...
}
OpenMP task
指令后面的代码块是一个显式任务。显式任务排队等待执行。 taskwait
指令的行为类似于barrier
,但适用于任务。另请参阅this answer类似的问题。
任务可以递归创建其他任务。因此,显式任务可用于处理图形和树木。但要注意开销 - 它比大多数其他构造的开销大,并且与来自schedule(dynamic)
的循环的开销非常相似。此外,任务中引用的外部作用域中的变量默认为firstprivate
。
请注意,显式任务是OpenMP 3.0中添加的功能。符合早期OpenMP版本的编译器可能不支持task
指令。几乎所有的现代编译器都支持OpenMP 3.0或更高版本,但Microsoft Visual C ++除外,它只支持OpenMP 2.0(即使在VS2012中)。