somik07
somik07

Reputation: 39

MPI broadcast array of strings

is it possible to broadcast array of strings defined as

char **lines;
lines = malloc(512 * sizeof(char*));

I have tried

MPI_Bcast(lines, linesCount, MPI_BYTE, 0, MPI_COMM_WORLD);

and

MPI_Bcast(lines, linesCount, MPI_CHAR, 0, MPI_COMM_WORLD);

where linesCount is number of strings in array.

How can it be achieved?

Upvotes: 3

Views: 2564

Answers (1)

atru
atru

Reputation: 4744

Assuming the strings that you store in the lines array may have a varying size, you can first broadcast an int array of sizes of each string and then broadcast each string separately,

/* Create an Array with length of each line 
   Broadcast it from process 0 */ 
int lin_siz[linesCount];
if (p_rank == 0)
    for (i=0; i < linesCount; i++)
        lin_siz[i] = strlen(lines[i])+1;
MPI_Bcast(&lin_siz, linesCount, MPI_INT, 0, MPI_COMM_WORLD);

/* Broadcast each line */
for (i=0; i < linesCount; i++)
    MPI_Bcast(&lines[i], lin_siz[i], MPI_CHAR, 0, MPI_COMM_WORLD);

MPI_Bcast can broadcast only elements that are contiguous in memory - in this case the int array with sizes, lin_siz and each line stored in lines. This may not be a very elegant solution and better is surely possible but it works.

It was tested with the following array

char **lines;
lines = malloc(linesCount * sizeof(char*));

if (p_rank == 0){
    for (i=0; i<linesCount-2; i++)
        lines[i] = "This is a test.";
    lines[i++] = "More testing.";
    lines[i++] = "Even more..";
}

with p_rank being a standard processor rank obtained with MPI_Comm_rank(MPI_COMM_WORLD, &p_rank). And successfully printed at the end as

/* Print */
printf("Process rank %d:\n", p_rank);
for (i=0; i < linesCount; i++)
     printf("%s\n", lines[i]);

I can post the entire test case if you have issues implementing my answer.

Upvotes: 2

Related Questions