If qFile.read(...) not enclosed in the if(rank==0){} tag, all processes will read the file. And queryDescriptors = new Descriptor[querySize]; should be called after the first MPI_Bcast() for all processes except 0: before, querySize does not make sense in these processes.
Process 0 should:
- read the number of items
- highlight
- read array
- broadcast number of items
- array transfer
Other processes should:
- get the number of elements
- highlight
- get an array
Here is an example of how to read a float array and use dynamic allocation:
#include <stdio.h>
Compile it with mpiCC main.cpp -o main and run mpirun -np 2 main
Another problem in your code is MPI_Type_contiguous(sizeof(Descriptor), MPI_SHORT, &descriptorType); . This should be MPI_Type_contiguous(sizeof(Descriptor), MPI_CHAR, &descriptorType); Here is a piece of code based on yours that should do the trick:
#include <stdio.h> #include <iostream> #include <fstream> #include <sys/types.h> #include <sys/stat.h> #include <unistd.h> #include <mpi.h> using namespace std; int main (int argc, char *argv[]) { int world_rank; int size; MPI_Init(&argc, &argv); MPI_Comm_size(MPI_COMM_WORLD, &size); MPI_Comm_rank(MPI_COMM_WORLD, &world_rank); int querySize; typedef short Descriptor[128]; MPI_Datatype descriptorType; MPI_Type_contiguous(sizeof(Descriptor), MPI_CHAR, &descriptorType); MPI_Type_commit(&descriptorType); Descriptor* queryDescriptors; if(world_rank == 0) { struct stat finfo; if(stat(argv[1], &finfo) == 0) { cout<<"st_size "<<finfo.st_size<<" descriptor "<<sizeof(Descriptor)<< endl; querySize = finfo.st_size/sizeof(Descriptor); cout<<"querySize "<<querySize<<endl; }else{ cout<<"stat error"<<endl; } { //read binary query queryDescriptors = new Descriptor[querySize]; fstream qFile(argv[1], ios::in | ios::binary); qFile.read((char*)queryDescriptors, querySize*sizeof(Descriptor)); qFile.close(); } } MPI_Bcast((void*)&querySize, 1, MPI_INT, 0, MPI_COMM_WORLD); if (world_rank != 0) { queryDescriptors = new Descriptor[querySize]; } MPI_Bcast((void*)queryDescriptors, querySize, descriptorType, 0, MPI_COMM_WORLD); cout<<"on rank "<<world_rank<<" rode "<<queryDescriptors[querySize/2][12]<<" on position "<<querySize/2<<endl; delete[] queryDescriptors; MPI_Finalize(); return 0; }
source share