Set number of threads using omp_set_num_threads() to 2, but omp_get_num_threads() returns 1

前端 未结 3 2015
孤独总比滥情好
孤独总比滥情好 2021-02-05 05:36

I have the following C/C++ code using OpenMP:

    int nProcessors=omp_get_max_threads();
    if(argv[4]!=NULL){
        printf(\"argv[4]: %s\\n\",argv[4]);
              


        
3条回答
  •  臣服心动
    2021-02-05 05:47

    It has been already pointed out that omp_get_num_threads() returns 1 in sequential sections of the code. Accordingly, even if setting, by omp_set_num_threads(), an overall number of threads larger than 1, any call to omp_get_num_threads() will return 1, unless we are in a parallel section. The example below tries to clarify this point

    #include 
    
    #include 
    
    int main() {
    
        const int maxNumThreads = omp_get_max_threads();
    
        printf("Maximum number of threads for this machine: %i\n", maxNumThreads);
    
        printf("Not yet started a parallel Section: the number of threads is %i\n", omp_get_num_threads());
    
        printf("Setting the maximum number of threads...\n");
        omp_set_num_threads(maxNumThreads);
    
        printf("Once again, not yet started a parallel Section: the number of threads is still %i\n", omp_get_num_threads());
    
        printf("Starting a parallel Section...\n");
    
    #pragma omp parallel for 
        for (int i = 0; i < maxNumThreads; i++) {
            int tid = omp_get_thread_num();
            printf("This is thread %i announcing that the number of launched threads is %i\n", tid, omp_get_num_threads());
        }
    
    }
    

提交回复
热议问题