编程语言
首页 > 编程语言> > c-如何在程序中设置OpenMP线程数?

c-如何在程序中设置OpenMP线程数?

作者:互联网

运行程序为

$OMP_NUM_TRHEADS=4 ./a.out

将活动OpenMP线程数限制为4,如htop所示.但是,如果不是在Bash中绑定OMP_NUM_THREADS环境变量,我会调用

setenv("OMP_NUM_THREADS", "4", 1);

从main调用任何启用OpenMP的功能之前,这似乎没有任何效果.

为什么会这样呢?如果有可能,如何在程序中设置OpenMP线程数?

解决方法:

有两种方法1可以用来设置程序中的线程数:

选项1

在打开并行区域的指令中使用num_threads子句:

#pragma omp parallel num_threads(number_of_threads)

选项#2

在并行区域开始之前,请使用omp_set_num_threads API函数:

#include <omp.h>

// ...
omp_set_num_threads(number_of_threads);
#pragma omp parallel

注意:这两个选项都比OMP_NUM_THREADS环境变量优先,但是num_threads子句优先于omp_set_num_threads.

Why setenv fails to have any effect?

这在OpenMP specification(强调我的)中涵盖:

Chapter 4

Environment Variables

[…] Modifications to the environment variables after the program has started, even if modified by the program itself, are ignored by the OpenMP implementation. However, the settings of some of the ICVs can be modified during the execution of the OpenMP program by the use of the appropriate directive clauses or OpenMP API routines. […]

1)第三个运行时选项允许更改执行并行区域的线程数,方法是将其重置为1(仅限主线程)或num_threads子句或omp_set_num_threads调用中的数字(它是if子句)在指令中该子句所属.

标签:multithreading,openmp,c-3,linux,c-4
来源: https://codeday.me/bug/20191121/2048202.html