VS2017 MPI环境配置

  1. 下载MPI,网址为:http://www.mpich.org/,选择windows版本的
  2. 按默认路径下载
  3. 右击项目->属性,进行配置:
    VC++目录->包含目录,添加:“C:\Program Files (x86)\Microsoft SDKs\MPI\Include;”
    VC++目录->库目录,添加:“C:\Program Files (x86)\Microsoft SDKs\MPI\Lib\x86;”
    右上角->配置管理器->活动解决方案平台,选择:x86;
    C/C++ -> 预处理器->预处理器定义,添加:“MPICH_SKIP_MPICXX;”
    C/C++ -> 代码生成 -> 运行库,选择:多线程调试(/MTd);
    链接器 -> 输入 -> 附加依赖项,添加:“msmpi.lib;”

  4. 输入程序

#define _CRT_SECURE_NO_WARNINGS

#include <stdio.h>
#include <mpi.h>
#include <string>
#include <cstring>
#include <cstdlib>
using namespace std;

const int MAX_STRLEN = 100;

int main(int argc, char **argv)
{
    char greeting[MAX_STRLEN];
    int comm_sz;
    int my_rank;
    MPI_Init(NULL, NULL);
    MPI_Comm_size(MPI_COMM_WORLD, &comm_sz);
    MPI_Comm_rank(MPI_COMM_WORLD, &my_rank);

    if (my_rank != 0) {
        sprintf(greeting, "Greetings from %d of %d", my_rank, comm_sz);
        MPI_Send(greeting, strlen(greeting) + 1, MPI_CHAR, 0, 0, MPI_COMM_WORLD);
    }
    else {
        printf("Greeting from %d of %d!\n", my_rank, comm_sz);
        for (int q = 1; q < comm_sz; q++) {
            MPI_Recv(greeting, MAX_STRLEN, MPI_CHAR, MPI_ANY_SOURCE, MPI_ANY_TAG, MPI_COMM_WORLD, MPI_STATUSES_IGNORE);
            printf("%s\n", greeting);
        }
    }
    MPI_Finalize();


    return 0;
}
  1. 编译后在命令行打开
    命令:mpiexec -n 10 MPI_test.exe #-n 10 表示开十个线程
  2. 运行结果
Greeting from 0 of 10!
Greetings from 4 of 10
Greetings from 1 of 10
Greetings from 3 of 10
Greetings from 2 of 10
Greetings from 6 of 10
Greetings from 9 of 10
Greetings from 8 of 10
Greetings from 7 of 10
Greetings from 5 of 10

由于不同线程指令执行的随机性,输出内容顺序可能不同

猜你喜欢

转载自blog.csdn.net/qq_36974075/article/details/81144807