我正在尝试使用OpenMP进行线程化,因为它是跨平台的。但是,当循环运行时,我无法解决如何在并行继续后生成代码?它基本上只是并行执行第一个循环但从未进入第二个非并行循环?
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());
}
}
答案 0 :(得分:3)
我认为你可以在你的omp并行块中将其中一个线程作为特殊线程
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());
}
}
}
}
如果没有更多详细信息,很难判断天气是否有意义。
您也可以使用sections
。例如: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: What is the benefit of nesting parallelizations?