gpt4 book ai didi

c++ - 在并行区域内有选择地启用 OpenMP for 循环

转载 作者:搜寻专家 更新时间:2023-10-31 02:12:49 25 4
gpt4 key购买 nike

是否可以使用模板参数或运行时变量有选择地启用 openmp 指令?

this (all threads work on the same for loop).
#pragma omp parallel
{
#pragma omp for
for (int i = 0; i < 10; ++i) { /*...*/ }
}
versus this (each thread works on its own for loop)
#pragma omp parallel
{
for (int i = 0; i < 10; ++i) { /*...*/ }
}

更新(测试if子句)

测试.cpp:

#include <iostream>
#include <omp.h>

int main() {
bool var = true;
#pragma omp parallel
{
#pragma omp for if (var)
for (int i = 0; i < 4; ++i) {
std::cout << omp_get_thread_num() << "\n";
}
}
}

错误消息(g++ 6,使用 g++ test.cpp -fopenmp 编译)

test.cpp: In function ‘int main()’:
test.cpp:8:25: error: ‘if’ is not valid for ‘#pragma omp for’
#pragma omp for if (var)
^~

最佳答案

有点变通。不知道是否可以摆脱获取线程 ID 的条件。

#include <iostream>
#include <omp.h>
#include <sstream>
#include <vector>
int main() {
constexpr bool var = true;
int n_threads = omp_get_num_procs();
std::cout << "n_threads: " << n_threads << "\n";
std::vector<std::stringstream> s(omp_get_num_procs());

#pragma omp parallel if (var)
{

const int thread_id0 = omp_get_thread_num();
#pragma omp parallel
{
int thread_id1;
if (var) {
thread_id1 = thread_id0;
} else {
thread_id1 = omp_get_thread_num();
}

#pragma omp for
for (int i = 0; i < 8; ++i) {
s[thread_id1] << i << ", ";
}
}
}

for (int i = 0; i < s.size(); ++i) {
std::cout << "thread " << i << ": "
<< s[i].str() << "\n";
}
}

输出(当 var == true 时):

n_threads: 8
thread 0: 0, 1, 2, 3, 4, 5, 6, 7,
thread 1: 0, 1, 2, 3, 4, 5, 6, 7,
thread 2: 0, 1, 2, 3, 4, 5, 6, 7,
thread 3: 0, 1, 2, 3, 4, 5, 6, 7,
thread 4: 0, 1, 2, 3, 4, 5, 6, 7,
thread 5: 0, 1, 2, 3, 4, 5, 6, 7,
thread 6: 0, 1, 2, 3, 4, 5, 6, 7,
thread 7: 0, 1, 2, 3, 4, 5, 6, 7,

输出(当 var == false 时):

n_threads: 8
thread 0: 0,
thread 1: 1,
thread 2: 2,
thread 3: 3,
thread 4: 4,
thread 5: 5,
thread 6: 6,
thread 7: 7,

关于c++ - 在并行区域内有选择地启用 OpenMP for 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42254482/

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