c++ - OpenMP:并行运行两个函数,每个函数占线程池的一半

标签 c++ c openmp

我有一个 CPU 消耗函数 do_long,我需要在两个不同的数据集上运行。

do_long(data1);
do_long(data2);

do_long() {
#pragma omp for
    for(...) {
        // do proccessing
    }
}

我有 N 个线程可用(取决于机器)。如何告诉 OpenMP 我想要 do_long 函数并行运行,N/2 个线程应该在第一个 do_long 中执行循环,另一个 N/2 应该处理第二个 do_long?

最佳答案

一种方法是使用嵌套并行来实现:

void do_long(int threads) {
#pragma omp parallel for num_threads(threads)
    for(...) {
        // do proccessing
    }
}


int main(){
    omp_set_nested(1);

    int threads = 8;
    int sub_threads = (threads + 1) / 2;

#pragma omp parallel num_threads(2)
    {
        int i = omp_get_thread_num();

        if (i == 0){
            do_long(data1, sub_threads);
        }
        if (i == 1 || omp_get_num_threads() != 2){
            do_long(data2, sub_threads);
        }
    }

    return 0;
}

关于c++ - OpenMP:并行运行两个函数,每个函数占线程池的一半,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7876156/

相关文章:

C++ 将数组复制到指针参数

c - 用c中的数组中的字符制作形状

c++ - OpenMP 未使用 Raspberry Pi 2 上的所有可用内核

c++ - 如何判断 OpenMP 是否正常工作?

c++ - OpenMP parallel-for 效率查询

C++ 编译器不会在默认参数结束前警告缺少参数

C++ 特殊成员函数

c++ - 指向数组的unique_ptr在调用release()后会自动释放动态内存吗?

c - 确定字符串是否为 C 中的有效 wchar_t*

c - 使用 scanf ("%i",var) 时,如果用户输入字母或仅按 Enter 键,我会遇到问题