OpenMP run threads but continue main

和自甴很熟 提交于 2019-12-08 02:45:15

问题


I am trying to use OpenMP for threading as it is cross platform. However I can't work out how to make the code after the parallel continue while the loop is running? It basically just executes the first loop in parallel but never gets to the second non parallel loop?

int main() {
    #pragma omp parallel 
        while(1) {
            Sleep(4000);
            printf("doing work in thread %d, nthreads %d\n", omp_get_thread_num(), omp_get_num_threads());
        }


    while (1) {
        Sleep(4000);
        printf("Hello from main %d, nthreads %d\n", omp_get_thread_num(), omp_get_num_threads());
    }
}

回答1:


I think you could just make one of the threads your special thread within your omp parallel block

int main() {
    #pragma omp parallel 
        if(omp_get_thread_num()==0){
             while(1) {
                Sleep(4000);
               printf("Hello from main %d, nthreads %d\n", omp_get_thread_num(), omp_get_num_threads());
             }
        }else{
             while(1) {
                Sleep(4000);
                printf("doing work in thread %d, nthreads %d\n", omp_get_thread_num(), omp_get_num_threads());
             }
         }
    }
}

Weather this makes sense in your case is hard to judge without more details.

You could also use sections. Example from here: http://bisqwit.iki.fi/story/howto/openmp/#Sections :

#pragma omp parallel // starts a new team
{
   //Work0(); // this function would be run by all threads.

   #pragma omp sections // divides the team into sections
   { 
     // everything herein is run only once.
     { Work1(); }
     #pragma omp section
     { Work2();
       Work3(); }
     #pragma omp section
     { Work4(); }
   }

   //Work5(); // this function would be run by all threads.
}

You can do nested renationalisation: OpenMP: What is the benefit of nesting parallelizations?



来源:https://stackoverflow.com/questions/9131875/openmp-run-threads-but-continue-main

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!