簡體   English   中英

為什么 std::vector.size() 不能與 MPI 一起使用?

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

當通過 MPI 接口發送/接收數據時,我在使用 std::vector 的 method.size() 時遇到了麻煩。 我創建了一個名為 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]} {}
    };

並且進程 0 應該向進程 1 和 2 發送一個名為dataset的點的某個 std::vector 。 首先,我創建了 MPI_Datatype:

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

然后實現消息傳遞:

#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 實際上正確接收了進程 0 發送的消息,如果嘗試打印它我得到了預期值,我的問題是 receive_buff.size() 返回 0 而它顯然是非空的,事實上 receive_buff.end( ) 返回與 receive_buff.begin() 相同的迭代器,但我真的不知道如何解決這個問題。 提前致謝。
我也嘗試了 MPI_Type_vector 和 MPI_Type_struct,但它也不起作用

首先,MPI對C++了解不多,你真正使用的是C接口。 所以接收不會做push_back :你給它一個足夠大的緩沖區,它把元素寫在那里。 (畢竟,你只傳遞給它buffer.data()所以 MPI 甚至不知道緩沖區是一個std::vector 。)

仍然可以詢問 receive 調用您收到了多少數據: MPI_Get_count(&status,yourtype,&count)返回消息中接收到的類型元素的數量。

順便說一句,MPI 有原生的 C++ 接口,例如 MPL,但即使它們不執行push_back到接收緩沖區:它們使用相同的機制來查詢狀態 object 的計數。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM