代码之家  ›  专栏  ›  技术社区  ›  heyula

如何在mpi中定义本地数组?

  •  0
  • heyula  · 技术社区  · 2 年前

    当我在mpi程序中定义一个数组时,所有处理器共享相同的地址,即相同的数组(指针)还是指向不同的数组(指示器)? 例如,int以下代码

    #include <mpi.h>
    #include <iostream>
    #include <fstream>
    #include <vector>
    
    int main(int argc, char** argv) {
        int num_procs, rank;
    
        // Initialize MPI
        int argcc=8;
        char **argvc;
        //print argc and argv
        std::cout << "argc: " << argc << std::endl;
        for (int i = 0; i < argc; ++i) {
            std::cout << "argv[" << i << "]: " << argv[i] << std::endl;
        }
        MPI_Init(&argcc, &argvc);
    
        // Get the number of processors
        MPI_Comm_size(MPI_COMM_WORLD, &num_procs);
    
        // Get the rank of the current process
        MPI_Comm_rank(MPI_COMM_WORLD, &rank);
    
        // Print the number of processors and the rank of the current process
        std::cout << "Number of processors: " << num_procs << std::endl;
        std::cout << "Rank: " << rank << std::endl;
        int count;
            
        if (rank == 0) {
            std::vector<int> numbers;
            std::ifstream inputFile("input.txt");
            int number;
            while (inputFile >> number) {
                numbers.push_back(number);
            }
            inputFile.close();
            // Print the numbers
            for (int i = 0; i < numbers.size(); ++i) {
                std::cout << "Number " << i << ": " << numbers[i] << std::endl;
            }
            // Send the one part of numbers to the other processes
             count = numbers.size() / (num_procs - 1);
            int offset = 0;
            for (int dest = 1; dest < num_procs; ++dest) {
                MPI_Send(&numbers[offset], count, MPI_INT, dest, 0, MPI_COMM_WORLD);
                offset += count;
            }
        }
        //create a vector to store the numbers
        std::vector<int> numbersx;
    
            // Receive the numbers from the root process
            MPI_Status status;
            MPI_Probe(0, 0, MPI_COMM_WORLD, &status);
            MPI_Get_count(&status, MPI_INT, &count);
            std::vector<int> numbers(count);
            MPI_Recv(&numbersx[0], count, MPI_INT, 0, 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE);
            // Print the numbers
            for (int i = 0; i < numbers.size(); ++i) {
                std::cout << "Number " << i << ": " << numbers[i] << std::endl;
            }
    
       
        // Finalize MPI
        MPI_Finalize();
    
        return 0;
    }
    
    

    numbersx数组是共享的,还是每个处理器都有自己单独的数组?或者,如果每个处理器都有自己的本地阵列,我应该怎么做?

    1 回复  |  直到 2 年前
        1
  •  1
  •   Victor Eijkhout    2 年前

    MPI是基于过程的。所以如果你的代码说 vector<int> x 然后每个进程在一个完全依赖于进程的地址上创建自己的矢量。你也可以把它看作:你分配的所有东西都是本地的;不存在全局数据结构。

    推荐文章