c++ - OpenMP 一次只执行一个线程

标签 c++ multithreading stl openmp

这是我的代码:

template <unsigned int DIM>
MyVector<DIM> MyVector<DIM>::operator+(MyVector& other) {
    MyVector ans = MyVector<DIM>();
    #pragma omp parallel for
    for (unsigned int i = 0; i < DIM; ++i)
    {
        std::cout << omp_get_thread_num() << std::endl;
        ans.values_[i] = values_[i] + other.values_[i];
    }
    return ans;
}

其中 values_ 是在 double 上模板化的 std::vector,DIM 类似于 1024。

我使用'g++ -std=c++14 -fopenmp -g'编译它

即使我有多个线程,我在不使用 OpenMP 时获得的性能也几乎没有差异。

的确,行:

std::cout << omp_get_thread_num() << std::endl;

显示线程一次执行一个...

输出很干净,类似于 11111...、22222...、00000...、33333... 并且 htop 始终只显示一个 100% 的核心,在整个执行过程中都是同一个核心.

我在几台机器上试过几个发行版,到处都是一样的。

最佳答案

您可能希望像这样重写代码以防止 I/O 的巨大开销(这或多或少也会序列化程序执行):

template <unsigned int DIM>
MyVector<DIM> MyVector<DIM>::operator+(MyVector& other) {
    MyVector ans = MyVector<DIM>();
    #pragma omp parallel
    {
        #pragma omp critical(console_io)
        {
            // The following are actually two function calls and a critical
            // region is needed in order to ensure I/O atomicity
            std::cout << omp_get_thread_num() << std::endl;
        }
        #pragma omp for schedule(static)
        for (unsigned int i = 0; i < DIM; ++i)
        {
            ans.values_[i] = values_[i] + other.values_[i];
        }
    }
    return ans;
}

确保 DIM 足够大,以便 OpenMP 的开销与正在完成的工作相比较小,同时又足够小,以便 vector 适合 CPU 的最后一级缓存。一旦后者不再是这种情况,您的循环就会受内存限制,添加新线程不会导致更快的计算。

关于c++ - OpenMP 一次只执行一个线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37471939/

相关文章:

c++ - 什么相当于 Linux 中的 Win32 消息泵?

c++ - 在 Arduino 上存储产品数据库

c++ - 在固定数量的线程之间划分数组

java - RestEasy 异步 Controller 正确使用

c++ - 如何对动态数组执行操作?

c++ - 为什么部分 Concurrency TS 不采用 C++17?

java - ProgressMonitorDialog 和 InvocableTargetException 中的取消按钮

string - 如何加快 STL 操作速度?

c++ - 为什么C++ STL不提供一套线程安全的容器?

c++ - 从文本文件C++填充对象