I'm trying to send some data to other processes using MPI_Bcast. I have multiple values that I try to send as string (using sprintf and sscanf to write and read them), but after calling broadcast values won't change. According to answer in this question it should work and set same values in all processes. Or am I missing something?
Here's the code:
char send[128]; int pointSize; double *x = new double; double *sigma = new double; double f_value; memset(send, 0, sizeof(send)); sprintf_s(send, "%d %p %p %lf", points.front().getSize(), points.front().getX(), points.front().getSigma(), points.front().getValue()); printf("[%d]:Before bcast: %s \n", rank, send); MPI_Barrier(MPI_COMM_WORLD); MPI_Bcast(&send, sizeof(send), MPI_CHAR, rank, MPI_COMM_WORLD); sscanf_s(send, "%d %p %p %lf", &pointSize, &x, &sigma, &f_value); printf("[%d]:After bcast: %d %p %p %lf \n", rank, pointSize, x, sigma, f_value); And output for 2 processes:
[1]:Before bcast: 10 0000007DAF2D1620 0000007DAF2D0D20 0.000015 [0]:Before bcast: 10 000000482E545A20 000000482E546560 0.000020 [0]:After bcast: 10 000000482E545A20 000000482E546560 0.000020 [1]:After bcast: 10 0000007DAF2D1620 0000007DAF2D0D20 0.000015
MPI_Bcastin a very strange manner.MPI_Bcastis typically sent from 1 process to all other processes. In your code, you are sending from each process to all processes.MPI_Bcastmight not be the tool you are looking for. ConsiderMPI_SendandMPI_Recvinstead?MPI_Bcast. I thought that first process which hitsMPI_Bcast(call is in loop) will send info to the others. Generally I want to send data from each process to all processes, but not at the same time, as I'm doing now, so I thinkMPI_Bcastmight do the job while I'll be changingrankin loop. Nonetheless, after calls from all processes, shouldn't they all have the same values insend? Values from lastMPI_Bcastcall, I suppose.mpi_bcastis a 'collective' operation, for it to work all processes involved in the communicator should call it 'at the same time'. One process, whose rank is passed as the 4th argument to the routine call, is the broadcast root, and you might want to think of that process 'sending' the broadcast to the other processes. But all processes call the broadcast. This is all very well documented in many places online. And then there arempi_alltoall,mpi_allgatherand othersMPI_Bcasta simpleif (root < size-1) root++; else root = 0;solves it (lines frommemsettoprintfare inwhileloop). As for sending pointers, thanks for pointing that out, in this case I'll try to do this some other way. Thanks again for everybody's help.