C++ omp 代码仅在一个线程上运行

C++ omp code working on only one thread

本文关键字:一个 线程 运行 代码 omp C++      更新时间:2023-10-16

我是OpenMP编程新手,我有一个问题。我找到了一个使用 OpenMP 的简单代码示例。代码生成成功,但代码仅在一个线程上运行。有一个代码:

#include <iostream>
#include <omp.h>
int main (int argc, const char * argv[])
{
    int nProcessors=omp_get_max_threads();
    std::cout<<nProcessors<<std::endl;

    omp_set_num_threads(nProcessors);
    std::cout<<omp_get_num_threads()<<std::endl;

#pragma omp parallel for 
    for(int i=0;i<5;i++){
        int tid=omp_get_thread_num();
        std::cout<<tid<<"t tid"<<std::endl;
        int nThreads=omp_get_num_threads();
        std::cout<<nThreads<<"t nThreads"<<std::endl;
    }

    exit(0);
}

它返回该结果:

4
1
0        tid
1        nThreads
0        tid
1        nThreads
0        tid
1        nThreads
0        tid
1        nThreads
0        tid
1        nThreads
Press any key to continue . . .

任何人都可以帮助我做错了什么?顺便说一下,我使用的是英特尔 i5 CPU。

谢谢亚历克斯,

我找到了一个解决方案,我需要做的一切都是在项目属性中启用 OMP:

项目属性>> C/C++>> 语言>>打开 MP 支持 = 是

相关文章: