"你好世界"使用OpenMP和MPI混合的C程序

时间:2016-02-06 21:37:11

标签: c mpi openmp

我想要一个'#34; hello world"使用OpenMP和MPI工作的程序。我从这里的例子开始

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();
}

我正在使用运行Ubuntu 12.10的双处理器Xeon工作站(2x6核心)。我可以毫无困难地使用MPI或OpenMP(但不是两者)来运行。

我使用命令

编译了上面的源代码
mpicc -fopenmp hello.c -o hello

然后使用

运行
export OMP_NUM_THREADS=4
mpirun ./hello -np 2 -x OMP_NUM_THREADS

以下是我得到的输出:

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

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

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

任何人都可以给我一个关于我做错的提示吗?据我所知,我正在复制上面链接中的示例。

1 个答案:

答案 0 :(得分:2)

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

变化:

mpirun ./hello -np 2 -x OMP_NUM_THREADS

分为:

mpirun -np 2 -x OMP_NUM_THREADS ./hello

旁注:我在我的机器上对此进行了测试。此处-np的默认值为3。在您的计算机上,默认值为1