gpt4 book ai didi

c - OpenMP 运行线程但继续主线程

转载 作者:行者123 更新时间:2023-12-04 05:59:08 26 4
gpt4 key购买 nike

我正在尝试使用 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());
}
}

最佳答案

我认为您可以将其中一个线程作为您的 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?

关于c - OpenMP 运行线程但继续主线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9131875/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com