OpenMP, for loop inside section

后端 未结 3 456
迷失自我
迷失自我 2020-12-06 08:28

I would like to run the following code (below). I want to spawn two independent threads, each one would run a parallel for loop. Unfortunately, I get an error. Apparently, p

3条回答
  •  旧巷少年郎
    2020-12-06 09:05

    Here you have to use nested parallelism. The problem with the omp for in the sections is that all the threads in scope have to take part in the omp for, and they clearly don't — they're broken up by sections. So you have to introduce functions, and do nested paralleism within the functions.

    #include 
    #include 
    
    void doTask1(const int gtid) {
        omp_set_num_threads(5);
    #pragma omp parallel 
        {
            int tid = omp_get_thread_num();
            #pragma omp for
            for(int i=0; i<5; i++) {
                printf("x %d %d %d\n", i, tid, gtid);
            }
        }
    }
    
    void doTask2(const int gtid) {
        omp_set_num_threads(5);
    #pragma omp parallel 
        {
            int tid = omp_get_thread_num();
            #pragma omp for
            for(int i=0; i<5; i++) {
                printf(". %d %d %d\n", i, tid, gtid);
            }
        }
    }
    
    
    int main()
    {
        omp_set_num_threads(2);
        omp_set_nested(1);
    
    #pragma omp parallel    
        {
            int gtid = omp_get_thread_num();
    #pragma omp sections
            {
    #pragma omp section
                doTask1(gtid);
    
    #pragma omp section
                doTask2(gtid);
            } // end parallel and end sections
        }
    }
    

提交回复
热议问题