使用 OpenMP 和 MPI 混合的“hello world”C 程序

j s*_*erg 5 c mpi openmp

我正在尝试创建一个同时使用 OpenMP 和 MPI 的“hello world”程序。我从这里的例子开始

http://www.slac.stanford.edu/comp/unix/farm/mpi_and_openmp.html

但我无法重现输出。这是我正在使用的确切来源:

#include <stdio.h>
#include <mpi.h>
#include <omp.h>

int main(int argc, char *argv[]) {
  int numprocs, rank, namelen;
  char processor_name[MPI_MAX_PROCESSOR_NAME];
  int iam = 0, np = 1;

  MPI_Init(&argc, &argv);
  MPI_Comm_size(MPI_COMM_WORLD, &numprocs);
  MPI_Comm_rank(MPI_COMM_WORLD, &rank);
  MPI_Get_processor_name(processor_name, &namelen);

  //omp_set_num_threads(4);

#pragma omp parallel default(shared) private(iam, np)
  {
    np = omp_get_num_threads();
    iam = omp_get_thread_num();
    printf("Hello from thread %d out of %d from process %d out of %d on %s\n",
           iam, np, rank, numprocs, processor_name);
  }

  MPI_Finalize();
}
Run Code Online (Sandbox Code Playgroud)

我使用的是运行 Ubuntu 12.10 的双处理器 Xeon 工作站(2x6 核)。我可以轻松地让使用 MPI 或 OpenMP(但不能同时使用两者)的程序运行。

我使用命令编译了上面的源代码

mpicc -fopenmp hello.c -o hello
Run Code Online (Sandbox Code Playgroud)

然后使用运行

export OMP_NUM_THREADS=4
mpirun ./hello -np 2 -x OMP_NUM_THREADS
Run Code Online (Sandbox Code Playgroud)

这是我得到的输出:

Hello from thread 0 out of 4 from process 0 out of 1 on SteinbergT5600Linux
Hello from thread 2 out of 4 from process 0 out of 1 on SteinbergT5600Linux
Hello from thread 1 out of 4 from process 0 out of 1 on SteinbergT5600Linux
Hello from thread 3 out of 4 from process 0 out of 1 on SteinbergT5600Linux
Run Code Online (Sandbox Code Playgroud)

根据这个例子,我应该得到这样的东西:

Hello from thread 0 out of 4 from process 0 out of 2 on SteinbergT5600Linux
Hello from thread 2 out of 4 from process 0 out of 2 on SteinbergT5600Linux
Hello from thread 1 out of 4 from process 0 out of 2 on SteinbergT5600Linux
Hello from thread 3 out of 4 from process 0 out of 2 on SteinbergT5600Linux
Hello from thread 0 out of 4 from process 1 out of 2 on SteinbergT5600Linux
Hello from thread 2 out of 4 from process 1 out of 2 on SteinbergT5600Linux
Hello from thread 1 out of 4 from process 1 out of 2 on SteinbergT5600Linux
Hello from thread 3 out of 4 from process 1 out of 2 on SteinbergT5600Linux
Run Code Online (Sandbox Code Playgroud)

谁能告诉我我做错了什么?据我所知,我完全复制了上面链接中的示例。

Cra*_*tey 2

您将程序名称指定为 的第一个参数mpirun,因此其余参数将被忽略(值得注意的是:-np 2)。因此,对于-np,您可以获得系统范围的默认值。

改变:

mpirun ./hello -np 2 -x OMP_NUM_THREADS
Run Code Online (Sandbox Code Playgroud)

进入:

mpirun -np 2 -x OMP_NUM_THREADS ./hello
Run Code Online (Sandbox Code Playgroud)

旁注:我在我的机器上测试了这个。这里的默认值-np3. 在你的机器上,默认值是1