MathLink and MPI
- To: mathgroup at smc.vnet.net
- Subject: [mg29420] MathLink and MPI
- From: Kashif Rasul <kashif at piglet.maths.monash.edu.au>
- Date: Tue, 19 Jun 2001 05:35:37 -0400 (EDT)
- Organization: Dept. of Maths. & Stats., Monash Uni., Clayton Aus.
- Sender: owner-wri-mathgroup at wolfram.com
Hello, I was wondering if anyone has tried using MathLink with MPI (message passing interface), with this I mean, a program that say gets its input from Mathematica via MathLink and does the calculation in parallel via MPI and returns the answer back to Mathematica again via MathLink. I was experimenting with such a program, and was curious to know what the best/most elegant way of doing this would be? The problem I think is that all the other processes need to know if MathLink is still up and hence continue waiting for a message but only one process needs to be running MathLink. What this does is that the other processes spend a lot of cpu waiting when the program is doing nothing. My example is a MathLink program to calculate pi: :Begin: :Function: mlpi :Pattern: mlpi[n_Integer] :Arguments: {n} :ArgumentTypes: {Integer} :Return: #include <mathlink.h> #include <mpi.h> double mlpi( int n ) { int myid, numprocs, i, retval=0; double mypi, pi, h, sum, x; MPI_Comm_size(MPI_COMM_WORLD,&numprocs); MPI_Comm_rank(MPI_COMM_WORLD,&myid); MPI_Bcast(&retval, 1, MPI_INT, 0, MPI_COMM_WORLD); MPI_Bcast(&n, 1, MPI_INT, 0, MPI_COMM_WORLD); h = 1.0 / (double) n; sum = 0.0; for (i = myid + 1; i <= n; i += numprocs) { x = h * ((double)i - 0.5); sum += (4.0 / (1.0 + x*x)); } mypi = h * sum; MPI_Reduce(&mypi, &pi, 1, MPI_DOUBLE, MPI_SUM, 0, MPI_COMM_WORLD); return pi; } int main( int argc, char *argv[] ) { int n, myid, numprocs, i, retval=0; double mypi, pi, h, sum, x; MPI_Init(&argc,&argv); MPI_Comm_rank(MPI_COMM_WORLD,&myid); MPI_Comm_size(MPI_COMM_WORLD,&numprocs); if (myid==0) { retval = MLMain(argc, argv); MPI_Bcast(&retval, 1, MPI_INT, 0, MPI_COMM_WORLD); } else { while (1) { MPI_Bcast(&retval, 1, MPI_INT, 0, MPI_COMM_WORLD); if (!retval) { MPI_Bcast(&n, 1, MPI_INT, 0, MPI_COMM_WORLD); h = 1.0 / (double) n; sum = 0.0; for (i = myid + 1; i <= n; i += numprocs) { x = h * ((double)i - 0.5); sum += (4.0 / (1.0 + x*x)); } mypi = h * sum; MPI_Reduce(&mypi, &pi, 1, MPI_DOUBLE, MPI_SUM, 0, MPI_COMM_WORLD); } else break; } } MPI_Finalize(); return 0; } I start it say on two processors as $ mpirun -np 2 mlpi -linkcreate $ Link created on: 34715 at ... and then l install and run it in Mathematica with: link = Install[LinkConnect["34715 at ..."]] mlpi[10] However when the program is doing nothing, one of the mlpi program takes a lot of cpu just waiting for me to call mlpi[...] again. I would appreciate any comments on this. Thanks in advance. Kashif