[英]MPI send struct with bytes array and integers
我想發送圖像數據(無符號字符數組),寬度和高度從等級0到等級1。什么是最好的方法? 我讀過要在MPI中發送復雜的數據結構,我們可以使用打包數據或創建自己的數據類型。 我的情況更好?
我試圖通過創建新的數據類型來做到這一點。 但是我遇到了錯誤: Segmentation fault (signal 11)
。 當我從結構中刪除數組時,它就可以工作了。 那么發送此數組有什么問題呢?
我的結構:
typedef struct MyImage {
int w;
int h;
unsigned char *data;
} image;
主要:
int main(int argc, char **argv) {
int size, rank;
MPI_Init(&argc, &argv);
MPI_Comm_size(MPI_COMM_WORLD, &size);
int blocksCount = 3;
int blocksLength[3] = {1, 1, 512 * 512 * 3};
// I also tried MPI_BYTE
MPI_Datatype types[3] = {MPI_INT, MPI_INT, MPI_UNSIGNED_CHAR};
MPI_Aint offsets[3];
MPI_Datatype custom_type;
offsets[0] = offsetof(image, w);
offsets[1] = offsetof(image, h);
offsets[3] = offsetof(image, data);
MPI_Type_create_struct(blocksCount, blocksLength, offsets, types, &custom_type);
MPI_Type_commit(&custom_type);
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
if (rank == 0) {
Mat mat = imread("/home/user/image.jpg", CV_LOAD_IMAGE_COLOR);
image send;
send.w = mat.size().width;
send.h = mat.size().height;
send.data = mat.data;
MPI_Send(&send, 1, custom_type, 1, 0, MPI_COMM_WORLD);
}
if (rank == 1) {
image recv;
MPI_Status status;
MPI_Recv(&recv, 1, custom_type, 0, MPI_ANY_TAG, MPI_COMM_WORLD, &status);
}
MPI_Type_free(&custom_type);
MPI_Finalize();
return 0;
}
發送方存在段錯誤,因為您嘗試從Mat.data
指針本身的位置而不是Mat.data
指向的內存位置開始發送數據。 接收器出現段錯誤,因為沒有空間來存儲768 KiB數據(任何到達)。
您可以先打包數據,但這將需要額外的緩沖區。 最好的選擇是只發送兩個消息:
Mat
對象; 有時,發送兩個消息而不是將所有內容打包到一個消息中會更好。
typedef struct MyImage {
int w;
int h;
} image;
int blocksCount = 2;
int blocksLength[2] = {1, 1};
MPI_Datatype types[2] = {MPI_INT, MPI_INT};
MPI_Aint offsets[2];
MPI_Datatype custom_type;
offsets[0] = offsetof(image, w);
offsets[1] = offsetof(image, h);
MPI_Type_create_struct(blocksCount, blocksLength, offsets, types, &custom_type);
MPI_Type_commit(&custom_type);
if (rank == 0) {
Mat mat = imread("/home/user/image.jpg", CV_LOAD_IMAGE_COLOR);
image send;
send.w = mat.size().width;
send.h = mat.size().height;
// Send image dimensions
MPI_Send(&send, 1, custom_type, 1, 0, MPI_COMM_WORLD);
// Send image data
MPI_Send(mat.data, send.w*send.h*3, MPI_UNSIGNED_CHAR, 1, 0, MPI_COMM_WORLD);
}
if (rank == 1) {
image recv;
MPI_Status status;
// Receive image dimensions
MPI_Recv(&recv, 1, custom_type, 0, 0, MPI_COMM_WORLD, &status);
// Allocate image matrix
Mat mat(Size(recv.w, recv.h), CV_8UC3);
// Receive image data
MPI_Recv(mat.data, recv.w*recv.h*3, MPI_UNSIGNED_CHAR, 0, 0, MPI_COMM_WORLD, &status);
...
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.