From: Zheng Yu Liang <zyliang@csis.hku.hk>
Newsgroups: comp.parallel.mpi
Subject: Start Threads in MPI
Date: Fri, 04 Sep 1998 21:11:12 +0800
Organization: HKU
Message-Id: <35EFE6EF.F62842F7@csis.hku.hk>
Mime-Version: 1.0
Content-Type: text/plain; charset=us-ascii
Content-Transfer-Encoding: 7bit


Hi,

We need start some  p_threads in mpi process. But when we start mpi with
two nodes , only process 0 enter the first thread and halt when the
thread return . Anyone know why? And can I call a mpi method in a
thread?

Our workstation is SMP with Linux 2.0.x , and mpich 1.1.0. Following is
our program:

#define INTERVALS 10000000

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <time.h>
#include "mpi.h"

volatile double pi = 0.0;  /* Approximation to pi (shared) */
pthread_mutex_t pi_lock;   /* Lock for above */

void * process(void *arg)
{
  register double width, localsum;
  register int i;
  register int iproc = (*((char *) arg) - '0');

  /* Set width */
  width = 1.0 / INTERVALS;

  /* Do the local computations */
  localsum = 0;
  for (i=iproc; i<INTERVALS; i+=2){
   register double x = (i + 0.5) * width;
    localsum += 4.0 / (1.0 + x * x);
  }
  localsum *= width;

  /* Lock pi for update, update it, and unlock */
  pthread_mutex_lock(&pi_lock);
  pi += localsum;
  pthread_mutex_unlock(&pi_lock);

printf("process end\n");
  return(NULL);  // HALT HERE
 }

int main(int argc, char **argv)
{
  pthread_t thread0, thread1;
  void * retval;
  clock_t start, end;

  int myid;
  float pi2, total_pi;

MPI_Init(&argc, &argv);
MPI_Comm_rank(MPI_COMM_WORLD, &myid);

printf("MPI_Init finish\n");
  /* Initialize the lock on pi */
  pthread_mutex_init(&pi_lock, NULL);

printf("pthread_init finish\n");
  start = times(NULL);

  /* Make the two threads */
  if (pthread_create(&thread0, NULL, process, "0") || // Enter the
thread and stop
      pthread_create(&thread1, NULL, process, "1")) {
    fprintf(stderr, "%s: cannot make thread\n", argv[0]);
    exit(1);
  }
printf("thread computation finish\n");
  /* Join (collapse) the two threads */
  if (pthread_join(thread0, &retval) || pthread_join(thread1, &retval)){

    fprintf(stderr, "%s: thread join failed\n", argv[0]);
    exit(1);
  }
pi2 = pi;
MPI_Reduce(&pi2, &total_pi, 1, MPI_FLOAT, MPI_SUM, 0, MPI_COMM_WORLD);
  end = times(NULL);

if(myid == 0)
{
  /* Print the result */
  printf("Number of Threads = 2\n");
  printf("Estimation of pi is %f\n", total_pi);
  printf("Execution time = %d clocks\n", (end - start));
}

  /* Check-out */
MPI_Finalize();
}

Thanks for your attention!

Jimmy

