gpt4 book ai didi

c - OpenMP始终在同一线程上工作

转载 作者:行者123 更新时间:2023-12-03 12:54:38 25 4
gpt4 key购买 nike

我正在使用OpenMP和C进行大学交付,并且正在尝试执行以下代码,我唯一想做的就是查看每个部分在每个不同线程中的工作方式:

#include <omp.h>
#include <stdio.h>
int main() {
int id, np;

printf("Max threads number: %d\n",omp_get_max_threads());
omp_set_num_threads(omp_get_max_threads());

#pragma omp parallel sections private(id, np)
{
np = omp_get_num_threads();
#pragma omp section
{
id = omp_get_thread_num();
printf("Hello from thread %d out of %d threads\n", id, np);
}
#pragma omp section
{
id = omp_get_thread_num();
printf("Hello from thread %d out of %d threads\n", id, np);
}
#pragma omp section
{
id = omp_get_thread_num();
printf("Hello from thread %d out of %d threads\n", id, np);
}
#pragma omp section
{
id = omp_get_thread_num();
printf("Hello from thread %d out of %d threads\n", id, np);
}
}
}

我正在Linux上工作,因此在编译时会说:
g++ prueba.c -lgomp -o prueba

我得到下一个输出:
Max threads number: 4
Hello from thread 0 out of 1 threads
Hello from thread 0 out of 1 threads
Hello from thread 0 out of 1 threads
Hello from thread 0 out of 1 threads

谁能告诉我为什么它总是在线程号0上工作,为什么omp_get_num_threads()总是为1?

我要实现的输出是:
Max threads number: 4
Hello from thread 0 out of 3 threads
Hello from thread 1 out of 3 threads
Hello from thread 2 out of 3 threads
Hello from thread 3 out of 3 threads

提前致谢!

最佳答案

首先,您缺少-fopenmp编译器标志,因此忽略了编译指示。在所有编译和链接步骤上指定fopenmp,除非必要,请勿手动与-lgomp链接。

第一句话

np = omp_get_max_threads();

如另一个答案所解释的, sections构造中的“内部”仍将被视为仅由单个线程执行的结构化块。因此,您的代码等于:
 #pragma omp parallel sections private(id)
{
#pragma omp section
{
np = omp_get_max_threads();
}
#pragma omp section
{
id = omp_get_thread_num();
printf("Hello from thread %d out of %d threads\n", id, np);
}
....

Note that you could also split the `parallel` / `sections` and initalize the private variables for each thread:

很好该代码由所有并行线程执行,并且 np(每个线程具有相同的值)通过工作共享 omp section保留。您甚至可以移动:
#pragma omp parallel
{
// Declaring the variables within makes them implicitly private
// and avoids stupid mistakes
int np = omp_get_max_threads();
int id = omp_get_thread_num();
#pragma omp sections
{
#pragma omp section
{
printf("Hello from thread %d out of %d threads\n", id, np);
}
...
}
}

关于c - OpenMP始终在同一线程上工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43952078/

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