作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在使用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);
}
}
}
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
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/
我是一名优秀的程序员,十分优秀!