openMP:为什么当我使用“; #pragma omp parallel num_threads(4)" [英] openMP:why am I not getting different thread ids when i uses " #pragma omp parallel num_threads(4)"
问题描述
当我使用"#pragma omp parallel num_threads(4)"时,为什么没有得到不同的线程ID.在这种情况下,所有线程ID均为0. 但是,当我注释该行并使用默认线程数时,我得到了不同的线程ID. 注意:-变量我使用变量tid来获取线程ID.
Why am I not getting different thread ids when I uses " #pragma omp parallel num_threads(4)". All the thread ids are 0 in this case. But when I comment the line and use default number of threads, I got different thread ids. Note:- variable I used variable tid to get thread id.
#include <omp.h>
#include <stdio.h>
#include <stdlib.h>
int main (int argc, char *argv[])
{
int nthreads, tid;
int x = 0;
#pragma omp parallel num_threads(4)
#pragma omp parallel private(nthreads, tid)
{
/* Obtain thread number */
tid = omp_get_thread_num();
printf("Hello World from thread = %d\n", tid);
// /* Only master thread does this */
if (tid == 0)
{
nthreads = omp_get_num_threads();
printf("Number of threads = %d\n", nthreads);
}
}
}
以上代码的输出:-
Hello World from thread = 0
Hello World from thread = 0
Number of threads = 1
Hello World from thread = 0
Number of threads = 1
Hello World from thread = 0
Number of threads = 1
Number of threads = 1
当我评论上述行时输出:-
Output when I comment the line mentioned above:-
Hello World from thread = 3
Hello World from thread = 0
Number of threads = 4
Hello World from thread = 1
Hello World from thread = 2
推荐答案
您正在创建两个嵌套的并行区域.与此操作相同:
You are creating two nested parallel regions. It is the same as doing this:
#pragma omp parallel num_threads(4)
{
#pragma omp parallel private(nthreads, tid)
{
/* Obtain thread number */
tid = omp_get_thread_num();
printf("Hello World from thread = %d\n", tid);
// /* Only master thread does this */
if (tid == 0)
{
nthreads = omp_get_num_threads();
printf("Number of threads = %d\n", nthreads);
}
}
}
omp_get_num_threads()
返回最内部区域中的线程数.因此,您正在执行四个线程,每个线程都在执行一个线程.
omp_get_num_threads()
returns the number of threads in the innermost region. So you are executing four threads, each of which is executing one thread.
内部并行区域仅执行一个线程,因为尚未启用嵌套并行性.您可以通过调用omp_set_nested(1)
启用它.
The inner parallel region is only executing one thread, because you haven't enabled nested parallelism. You can enable it by calling omp_set_nested(1)
.
http://docs.oracle.com/cd/E19205-01 /819-5270/aewbi/index.html
如果要创建单个并行区域并指定两个属性,而不是创建两个嵌套的并行区域,则可以执行以下操作:
If instead of making two nested parallel regions, you wanted to make a single parallel region and specify two properties, you can do this:
#pragma omp parallel num_threads(4) private(nthreads,tid)
{
.
.
.
}
这篇关于openMP:为什么当我使用“; #pragma omp parallel num_threads(4)"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!