简体   繁体   中英

Why doesn't std::vector.size() work with MPI?

I've troubles using the method.size() of std::vector when data are sent/received through the MPI interface. I created a custom type named point

template<typename T>
struct point{
        T data[ndim];
        point() = default;
        point(const T& a, const T& b): data{a,b} {} // not correct
        point(const T&& a, const T&&b): data{std::move(a),std::move(b)} {}
        explicit point(const point& mypoint): data{mypoint.data[0], mypoint.data[1]} {}
    };

And the process 0 is supposed to send to process 1 and 2 a certain std::vector of point named dataset . First I've created the MPI_Datatype:

MPI_Datatype MPI_point; // custom datatype
MPI_Type_contiguous(2, MPI_FLOAT,&MPI_point);
MPI_Type_commit(&MPI_point);

and then implemented the message passaging:

#define count 10
 MPI_Init ( NULL, NULL );
 std::vector<point<float>> receive_buff;
 receive_buff.reserve(count)
 int rank;
 int size;   
 MPI_Comm_rank(MPI_COMM_WORLD, &rank);
 MPI_Comm_size(MPI_COMM_WORLD, &size);
 if(rank==0){ 
        MPI_Send(dataset.data(), count, MPI_point, 1,1,MPI_COMM_WORLD);
        MPI_Send(dataset.data(), count, MPI_point, 2,2,MPI_COMM_WORLD);
    }
else{
        MPI_Recv(receive_buff.data(),count,MPI_point, 0,rank,MPI_COMM_WORLD, &status);
}

receive_buff actually receive correctly the messagge sent by process 0, and if a try to print it I get the expected value, my issue is that receive_buff.size() return 0 while it's clearly non-empty, as matter of fact receive_buff.end() return the same iterator of receive_buff.begin(), but I don't really know how to fix this. Thanks in advance.
I tried also MPI_Type_vector, and MPI_Type_struct, but it doesn't work either

First of all, MPI doesn't know much about C++, you're really using the C interface. So receiving does not do a push_back : you give it a buffer that's large enough and it writes the elements in there. (And after all, you only pass it buffer.data() so MPI doesn't even know that the buffer is a std::vector .)

It is still possible to ask the receive call how much data you received: MPI_Get_count(&status,yourtype,&count) returns how many elements of the type received were in the message.

By the way, there are native C++ interfaces to MPI, such as MPL, but even they don't do push_back into the receive buffer: they use the same mechanism of querying the count of the status object.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM