
#include <stdio.h>
#include "pvm3.h"
#define SLAVENAME "slave1"

main()
{
    int mytid;                  /* my task id */
	int tids[32];				/* slave task ids */
    int n, nproc, numt, i, who, msgtype, nhost, narch;
    float data[100], result[32];
    struct pvmhostinfo *hostp[32];

    /* enroll in pvm */
    mytid = pvm_mytid();

    /* Set number of slaves to start */
    /* Can not do stdin from spawned task */
    if( pvm_parent() == PvmNoParent ){
       puts("How many slave programs (1-32)?");
       scanf("%d", &nproc);
    }
    else{
       pvm_config( &nhost, &narch, hostp );
       nproc = nhost;
       if( nproc > 32 ) nproc = 32 ;
    }

    /* start up slave tasks */
    numt=pvm_spawn(SLAVENAME, (char**)0, 0, "", nproc, tids);
    if( numt < nproc ){
       printf("Trouble spawning slaves. Aborting. Error codes are:\n");
       for( i=numt ; i<nproc ; i++ ) {
          printf("TID %d %d\n",i,tids[i]);
       }
       for( i=0 ; i<numt ; i++ ){
          pvm_kill( tids[i] );
       }
       pvm_exit();
       exit();
    }
    

    /* Begin User Program */
    n = 100;
    /* initialize_data( data, n ); */
    for( i=0 ; i<n ; i++ ){
       data[i] = 1;
    }

    /* Broadcast initial data to slave tasks */
	pvm_initsend(PvmDataDefault);
	pvm_pkint(&nproc, 1, 1);
	pvm_pkint(tids, nproc, 1);
	pvm_pkint(&n, 1, 1);
	pvm_pkfloat(data, n, 1);
    pvm_mcast(tids, nproc, 0);

    /* Wait for results from slaves */
    msgtype = 5;
    for( i=0 ; i<nproc ; i++ ){
       pvm_recv( -1, msgtype );
       pvm_upkint( &who, 1, 1 );
       pvm_upkfloat( &result[who], 1, 1 );
       printf("I got %f from %d\n",result[who],who);
    }
    /* Program Finished exit PVM before stopping */
    pvm_exit();
}

