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

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

  • 1
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值