OpenMP运行线程,但继续主线程 [英] OpenMP run threads but continue main

查看:306
本文介绍了OpenMP运行线程,但继续主线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用OpenMP进行线程化,因为它是跨平台的.但是我不知道如何在循环运行时继续并行执行之后使代码生效?它基本上只是并行执行第一个循环,而从未执行到第二个非并行循环?

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());
    }
}

推荐答案

我认为您可以将一个线程作为omp并行块中的特殊线程

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.

您也可以使用sections.此处的示例: http://bisqwit.iki.fi/story/howto/openmp /#Sections :

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.
}

您可以进行嵌套的重新国有化: OpenMP:这样做有什么好处?嵌套并行化?

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

这篇关于OpenMP运行线程,但继续主线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆