环境配置
然后跑这个代码测试即可
// 命令行参数:
//mpiexec -n 9 "C:\Users\ASUS\Desktop\testMPI\MPIv2.exe"
//在官网下载 msmpi.exe 和 msmpi.msi ,exe 是运行环境,msi是 MinGW 头文件,lib库的集合
//https://blog.csdn.net/weixin_45942927/article/details/125167460
#include <iostream>
#include <mpi/mpi.h>
// 把库文件加入MinGW的include 库里,然后 lib 库也加入 x64的三个文件 ,然后链接库加上 --lmsmpi
// cmd 运行才能跑多核,我的小熊猫C++2.25.1直接运行会变成单线程
#include <stdint.h>
#include <windows.h>
#include <io.h>
using namespace std;
//https://blog.csdn.net/weixin_45942927/article/details/125167460
int main(int argc, char* argv[]) {
Sleep(20);
cout << "hello" << endl;
int myid, numprocs;
int namelen;
char processor_name[MPI_MAX_PROCESSOR_NAME];
MPI_Init(&argc, &argv);
MPI_Comm_rank(MPI_COMM_WORLD, &myid);
MPI_Comm_size(MPI_COMM_WORLD, &numprocs);
MPI_Get_processor_name(processor_name, &namelen);
// MPI 下 fopen 在 Windows读写失败,不能用相对路径 穷举测试得到结论
// windows 的 msmpi 相对路径不能读取,只能用绝对路径,但是可以通过获取当前文件所在文件夹来拼出来绝对路径
if (myid == 0) {
FILE* fp;
// fp=fopen("matrix.txt","w");
fp = fopen("C:\\Users\\ASUS\\Desktop\\matrix45.txt", "w");
fprintf(fp, "hello\n");
fclose(fp);
printf("%s\n", _pgmptr); // 获取当前文件路径
char path[PATH_MAX+100]; //PATH_MAX is defined in limits.h
getcwd(path, sizeof(path)); // io.h 获取当前文件夹位置
printf("%s\n", path);
strcat(path,"\\matrixv4.txt");
printf("%s\n",path);
fp=fopen(path,"w");
fprintf(fp, "hello\n");
fclose(fp);
}
MPI_File mpi_file;
string fname("C:\\Users\\ASUS\\Desktop\\testv8.txt"); // 在桌面创建文件
if (MPI_File_open(MPI_COMM_WORLD, fname.c_str(), MPI_MODE_CREATE | MPI_MODE_WRONLY, MPI_INFO_NULL, &mpi_file) != MPI_SUCCESS)
{
cout << "Error opening file!" << endl;
exit(0);
}
string string_out;
string_out = string("This data has been written by") + to_string(myid) + string("\n");
MPI_File_write_ordered(mpi_file, string_out.c_str(), (int)string_out.length(), MPI_CHAR, MPI_STATUS_IGNORE);
MPI_File_close(&mpi_file);
std::cout << "Hello World! Process " << myid << " of " << numprocs << " on " << processor_name << std::endl;
MPI_Finalize();
return 0;
}