OpenMP 如何知道嵌套了多少个循环实例?

How can OpenMP know how many loop instances are nested?

很久以前我在写c++程序的时候就用过OpenMP。 突然,我想到了一个问题。

"How can OpenMP know how many loop instances are nested?"

是否被编译器显式统计?

OpenMP 运行时 在线程局部变量中跟踪此信息。

可能是目前最流行的 OpenMP 实现之一,libgomp 是开源的;这意味着人们不仅可以阅读其文档,还可以完全免费阅读其源代码。

omp_get_level()的实现是here:

int
omp_get_level (void)
{
  return gomp_thread ()->ts.level;
}

gomp_thread()的实现是here。它检索指向线程局部结构的指针。

#if defined __nvptx__
extern struct gomp_thread *nvptx_thrs __attribute__((shared));
static inline struct gomp_thread *gomp_thread (void)
{
  int tid;
  asm ("mov.u32 %0, %%tid.y;" : "=r" (tid));
  return nvptx_thrs + tid;
}
#elif defined HAVE_TLS || defined USE_EMUTLS
extern __thread struct gomp_thread gomp_tls_data;
static inline struct gomp_thread *gomp_thread (void)
{
  return &gomp_tls_data;
}
#else
extern pthread_key_t gomp_tls_key;
static inline struct gomp_thread *gomp_thread (void)
{
  return pthread_getspecific (gomp_tls_key);
}
#endif

数据结构 ts 是一个 struct gomp_team_state,除其他外,contains:

  [...]
  /* Nesting level.  */
  unsigned level;

  /* Active nesting level.  Only active parallel regions are counted.  */
  unsigned active_level;
  [...]

并且每当使用 #pragma omp parallel 时,编译器都会将并行部分的主体提取到一个子函数中,并生成一组复杂的函数调用,最终导致 gomp_team_start()contains:

#ifdef LIBGOMP_USE_PTHREADS
void
gomp_team_start (void (*fn) (void *), void *data, unsigned nthreads,
                 unsigned flags, struct gomp_team *team)
{

  [...]

  ++thr->ts.level;
  if (nthreads > 1)
    ++thr->ts.active_level;