从进程无法访问更新的全局值

问题描述 投票:0回答:0

在下面的代码中,我在主进程中更改

total_b_points
的值。我已在代码中将其声明为全局。但是这个值在从属进程中是不会改变的。这是一个使用 2 个进程的 MPI 代码。 请指导我如何让它工作。

#include <iostream>
#include <mpi.h>
#include<string>
#include <bits/stdc++.h>

int total_b_points=0;

int main(int argc, char * argv[]){        
    MPI_Init(&argc,&argv);
    int pid;
    int np;   

    MPI_Comm_size(MPI_COMM_WORLD, &np);
    MPI_Comm_rank(MPI_COMM_WORLD, &pid);
    if(pid==0){
        std::vector<double> values ={33,334,5,43};
        total_b_points = values.size();
        std::cout << "The value of total_b_points= " <<total_b_points<< std::endl;
    }

    //slave processes
    else{
        std::cout << "Printing the value of total_b_points in Slave  "<< total_b_points<< std::endl;
    }
    MPI_Finalize();      
}

Start: 2023-04-11_15:05:40
The value of total_b_points= 4
Printing the value of total_b_points in Slave  0
Stop: 2023-04-11_15:05:42

编辑 我已经解决了这个问题。谢谢大家。这个解决方案工作正常。

#include <iostream>
#include <mpi.h>
#include<string>
#include <bits/stdc++.h>
#include <atomic>

std::atomic<int> total_b_points;
// int total_b_points=0;

int main(int argc, char * argv[]){
    MPI_Init(&argc,&argv);
    int pid;
    int np;
    
    MPI_Comm_size(MPI_COMM_WORLD, &np);
    MPI_Comm_rank(MPI_COMM_WORLD, &pid);

    if(pid==0){
        std::vector<double> values ={33,334,5,43};
        total_b_points = values.size();
        std::cout << "The value of total_b_points= " <<total_b_points<< std::endl;
        // broadcast the value of total_b_points to all other processes
        MPI_Bcast(&total_b_points, 1, MPI_INT, 0, MPI_COMM_WORLD);
    }
    //slave processes
    else{
        // receive the value of total_b_points from the master process
        MPI_Bcast(&total_b_points, 1, MPI_INT, 0, MPI_COMM_WORLD);
        int value = total_b_points;

        std::cout << "Printing the value of total_b_points in Slave  "<< value<< std::endl;
    }
    MPI_Finalize();
}
c++ mpi
© www.soinside.com 2019 - 2024. All rights reserved.