【发布时间】:2017-05-13 10:34:19
【问题描述】:
我正在使用 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
提前致谢!
【问题讨论】:
标签: c multithreading parallel-processing openmp