Ejemplo n.º 1
0
main()
{
	char *me = "inheritb";
	int context_original, context_1, context_2;
	int ptid, tid, gptid, cc;
	char buf[100];
	char machine[25];
	int i=0;

	gethostname( machine, 25 );

	printf( "%d:%s: t%x on machine <%s> with context %d.\n",
			i++, me, pvm_mytid(), machine, pvm_getcontext() );

	context_original = pvm_getcontext(); /* retrieve initial context */

	context_1 = pvm_newcontext();		 /* get new context 1 */
	pvm_setcontext( context_1 );		 /* activate new context 1 */

	printf( "%d:%s: t%x on machine <%s> with new #1 context %d ",
			i++, me, pvm_mytid(), machine, pvm_getcontext() );
	printf( "--> spawn 1st inherit2.\n" );

	/* start 1st inherit2 worker @ context 1 */
	pvm_spawn( "inherit2", (char **) 0, PvmTaskDefault, "", 1, &tid );

	context_2 = pvm_newcontext();		 /* get new context 2 */
	pvm_setcontext(context_2);			 /* activate new context 2 */

	printf( "%d:%s: t%x on machine <%s> with new #2 context %d ",
			i++, me, pvm_mytid(), machine, pvm_getcontext() );
	printf( "--> spawn 2nd inherit2.\n" );

	/* start 2nd inherit2 worker @ context 2 */
	pvm_spawn( "inherit2", (char **) 0, PvmTaskDefault, "", 1, &tid );

	/* receive from inherit2 worker 2 @ context 2 */
	cc = pvm_recv( -1, -1 );
	pvm_bufinfo( cc, (int *) 0, (int *) 0, &tid );
	pvm_upkstr( buf );
	printf( "%d:%s: t%x %s <-- received from 2nd inherit2.\n",
			i++, me, tid, buf);

	/* reactivate initial context 1*/
	pvm_setcontext(context_1);

	printf( "%d:%s: t%x on machine <%s> with new #1 context %d.\n",
			i++, me, pvm_mytid(), machine, pvm_getcontext() );

	/* receive from inherit2 worker 1 @ context 1 */
	cc = pvm_recv( -1, -1 );
	pvm_bufinfo( cc, (int *) 0, (int *) 0, &tid );
	pvm_upkstr( buf );
	printf( "%d:%s: t%x %s <-- received from 1st inherit2.\n",
			i++, me, tid, buf );

	pvm_exit();
	exit( 0 );
}
Ejemplo n.º 2
0
int main(int argc, char **argv) {
    int nproc, status;
    int tids[SLAVENUM], ok, mytid;
    nproc = pvm_spawn("sort_slave",0,PvmTaskDefault, "LINUX64",SLAVENUM, tids);
    printf("Master id %d\n", nproc );
    //app for sorting
    do {
        status = 0;
        //if 0 - all done
        //if 1 - continue
        for(int i = 0; i < SLAVENUM; i++) {
            int slave_status ;
            pvm_recv (-1 , TAG_SLAVE);
            pvm_upkint(&slave_status, 1, 1);
            if (slave_status == 0) {
                status = 1;
            }
        }
        for (int i = 0; i < SLAVENUM; ++i) {
            pvm_initsend( PvmDataRaw );
            pvm_pkint(&status, 1, 1);
            pvm_send( tids[i], TAG_MASTER );
        }
    } while(status == 1);
    printf("Master end!");
    pvm_exit();
}
Ejemplo n.º 3
0
Archivo: px.cpp Proyecto: Mityuha/gspp
int main(int argc, char* argv[])
{
	setbuf(stdout, NULL);
	double x;
	srand(time(NULL));
	if (argc == 2)
		x = atof(argv[1]);
	else
		x = ((double)rand() / (RAND_MAX));
	printf("[p(x)]:Hello! I'm p(x). I check condition if x < 0.5\n") ;
	printf("[p(x)]:x = %lf\n", x);

	char name[8];
	if (x < 0.5)
		strcpy(name, "f1x");
	else
		strcpy(name, "f2x");

	char* args[2];
	char buf[32];
	sprintf(buf, "%lf", x);
	args[0] = buf;
	args[1] = '\0';
	int tid;
	printf("[p(x)]: spawning %s\n", name);
	int code = pvm_spawn(name, args, 0, "", 1, &tid);
	//printf("[p(x)]: pvm_spawn returns code %d\n", code);

	return 0;
}
Ejemplo n.º 4
0
int main(int argc, char **argv){
	NodoBusqueda nodo_problema;
	int mintareas=4, cantidad_tareas, numt, *tids=NULL,i;
	GList *tareas, *tarptr;
	NodoBusqueda solucion;
	int problema[_SUDOK_FILAS][_SUDOK_COLUMNAS] = {		{1,0,0,0,0,7,0,9,0},
														{0,3,0,0,2,0,0,0,8},
														{0,0,9,6,0,0,5,0,0},
														{0,0,5,3,0,0,9,0,0},
														{0,1,0,0,8,0,0,0,2},
														{6,0,0,0,0,4,0,0,0},
														{3,0,0,0,0,0,0,1,0},
														{0,4,0,0,0,0,0,0,7},
														{0,0,7,0,0,0,3,0,0}

												};

	inicializarMatrizAdyacencia();
	nodo_problema= nodoInicial(problema);

	tareas=generarTareas(nodo_problema,mintareas);
	cantidad_tareas = g_list_length(tareas);
	tids=malloc(sizeof(int)*cantidad_tareas);

	numt=pvm_spawn("sudokuterm",NULL,0,"",cantidad_tareas,tids);

	if(numt<cantidad_tareas){
		fprintf(stderr, "ERROR. sudokuhub: no se pudo hacer spawn de todas las tareas");
		exit(1);
	}

	//iteramos sobre las tareas y les pasamos los datos
	tarptr=g_list_first(tareas);
	for(i=0;i<cantidad_tareas;i++){
		pvm_initsend(PvmDataDefault);
		pvm_pkNodoBusqueda((NodoBusqueda*)(tarptr->data));
		pvm_send(tids[i],_TIPOMSG_NODOBUSQUEDA);
		tarptr=tarptr->next;
	}

	//esperamos las respuestas y velamos por una solucion
	for(i=0;i<cantidad_tareas;i++){
		int exitofracaso,j;
		pvm_recv(tids[i],_TIPOMSG_EXITOFRACASO);
		pvm_upkint(&exitofracaso,1,1);
		if(exitofracaso==1){
			pvm_recv(tids[i],_TIPOMSG_NODOBUSQUEDA);
			pvm_upkNodoBusqueda(&solucion);
			printf("\nSE ENCONTRO UNA SOLUCION\n");
			printNodoBusqueda(&solucion);
			for(j=0;j<cantidad_tareas;j++)
				pvm_kill(tids[j]);
			pvm_exit();
			exit(0);
		}
	}
	printf("\nNO SE ENCONTRO NINGUNA SOLUCION\n");

	return 0;
}
Ejemplo n.º 5
0
void pvm_init(int argc, char *argv[])
{
    int mytid, mygid, ctid[MAXPROC];
    int np, i;

    mytid = pvm_mytid();
    if((argc != 2) && (argc != 1)) goto usage;
    if(argc == 1) np = 1;
    if(argc == 2)
       if((np = atoi(argv[1])) < 1) goto usage;
    if(np > MAXPROC) goto usage;

    mygid = pvm_joingroup(MPGROUP);

    if(np > 1)
       if (mygid == 0) 
          i = pvm_spawn(argv[0], argv+1, 0, "", np-1, ctid);

    while(pvm_gsize(MPGROUP) < np) sleep(1);

    /* sync */
    pvm_barrier(MPGROUP, np);
    
    printf("PVM initialization done!\n");
    
    return;

  usage:
    fprintf(stderr, "usage: %s <nproc>\n", argv[0]);
    pvm_exit();
    exit(-1);
}
Ejemplo n.º 6
0
void pvmfspawn (WatcomFortranStr *aout_str, int *flag, WatcomFortranStr *where_str, int *count, int *tids, int *info)
{
   char* aout_ptr  = aout_str->strP;
   int   aout_len  = aout_str->len;
   char* where_ptr = where_str->strP;
   int   where_len = where_str->len;
#else
void __stdcall
PVMFSPAWN (char *aout_ptr,int aout_len, int *flag, char *where_ptr,int where_len, int *count, int *tids, int *info)
{
#endif

   char taout[MAX_PROC_NAME + 1];
   char twhere[MAX_HOST_NAME + 1];
   /*
    * Copy the program and where names to make sure there's
    * a NUL at the end.
    */
   
   if (ftocstr(taout, sizeof(taout), aout_ptr, aout_len)) {
      *info = PvmBadParam;
      return;
   }
   
   /*
    * if the where parameter is '*', pass a NULL pointer to
    * initiate which will allow execution on any machine.
    */

   if (*(where_ptr) == '*') {
      *info = pvm_spawn(taout, (char**)0, *flag, "", *count, tids);

   } else {
      if (ftocstr(twhere, sizeof(twhere), where_ptr, where_len)) {
         *info = PvmBadParam;
         return;
      }
   
      *info = pvm_spawn(taout, (char**)0, *flag, twhere, *count, tids);

   }
}
Ejemplo n.º 7
0
/* 
   Create the PE Tasks. We spawn (nPEs-1) pvm threads: the Main Thread 
   (which starts execution and performs IO) is created by forking SysMan 
*/
static int
createPEs(int total_nPEs) {
  int i, spawn_nPEs, iSpawn = 0, nArch, nHost;
  struct pvmhostinfo *hostp; 
  int sysman_host;

  spawn_nPEs = total_nPEs-1;
  if (spawn_nPEs > 0) {
    IF_PAR_DEBUG(verbose,
		 fprintf(stderr, "==== [%x] Spawning %d PEs(%s) ...\n", 
			 sysman_id, spawn_nPEs, petask);
		 fprintf(stderr, "  args: ");
		 for (i = 0; pargv[i]; ++i)
		   fprintf(stderr, "%s, ", pargv[i]);
		 fprintf(stderr, "\n"));

    pvm_config(&nHost,&nArch,&hostp);
    sysman_host=pvm_tidtohost(sysman_id);
	
    /* create PEs on the specific machines in the specified order! */
    for (i=0; (iSpawn<spawn_nPEs) && (i<nHost); i++)
      if (hostp[i].hi_tid != sysman_host) { 
	checkComms(pvm_spawn(petask, pargv, spawn_flag+PvmTaskHost, 
			     hostp[i].hi_name, 1, gtids+iSpawn),
		   "SysMan startup");
	IF_PAR_DEBUG(verbose,
		     fprintf(stderr, "==== [%x] Spawned PE %d onto %s\n",
			     sysman_id, i, hostp[i].hi_name));
	iSpawn++;
      }
      
    /* create additional PEs anywhere you like */
    if (iSpawn<spawn_nPEs) { 
      checkComms(pvm_spawn(petask, pargv, spawn_flag, "", 
			   spawn_nPEs-iSpawn, gtids+iSpawn),
		 "SysMan startup");
	IF_PAR_DEBUG(verbose,
		     fprintf(stderr,"==== [%x] Spawned %d additional PEs anywhere\n",
			     sysman_id, spawn_nPEs-iSpawn));
      }   
    }
Ejemplo n.º 8
0
int CreateSlaves(int *SeisSlaves, char *SlaveName, int pn)
{
  int info;

  info = pvm_spawn(SlaveName, (char **)0, 0,
                   (char *)0, pn, SeisSlaves);
  if (info != pn) {
        fprintf(stderr, "Error starting pvm applications %s \n", SlaveName);
        return(-1);
  }
  return(pn);
} /* End of CreateSlaves */
Ejemplo n.º 9
0
int spawn(char *task, char **argv, int flag, char *where, int ntask,
	  int *tids)
{
   int status;
   
   if ((status = pvm_spawn(task, argv, flag, where, ntask, tids)) != ntask){
      printf("Couldn't start %s!! \n", task);
      PVM_ERROR(*tids);
      exit(0);
   }
   return(status);
}
Ejemplo n.º 10
0
main()
{
	int cc, tid;
	char buf[100];

	printf("i'm t%x\n", pvm_mytid());

	cc = pvm_spawn("hello_other", (char**)0, 0, "", 1, &tid);

	if (cc == 1) {
		cc = pvm_recv(-1, -1);
		pvm_bufinfo(cc, (int*)0, (int*)0, &tid);
		pvm_upkstr(buf);
		printf("from t%x: %s\n", tid, buf);

	} else
		printf("can't start hello_other\n");

	pvm_exit();
	exit(0);
}
Ejemplo n.º 11
0
// Set up the PVM stuff.  Register this task then set up all of the slaves.
// Return 1 if a problem, 0 if everything went ok.
int
StartupPVM(const char* prog, PVMData& d) {
  int i;

  d.masterid = pvm_mytid();
  
  int nhost, narch;
  struct pvmhostinfo* hostp;
  int status = pvm_config(&nhost, &narch, &hostp);
  if(status == PvmSysErr) {
    cerr<<"\n" << prog << ": PVM not responding. Have you started the PVM?\n";
    return 1;
  }
  
  d.tid = new int [d.nreq];	// task IDs for the slaves
  d.ntasks = pvm_spawn(SLAVE_NAME, (char**)0, 0, "", d.nreq, d.tid);
  if(d.ntasks <= 0) {
    cerr << prog << ": Error spawning slaves.\n";
    cerr << "  Error codes of failed spawns are:\n";
    for(i=0; i<d.nreq; i++) {
      cerr << "    slave "; cerr.width(3);
      cerr << i << ": " << d.tid[i] << "\n";
    }
    pvm_exit();
    return 1;
  }
  else if(d.ntasks < d.nreq) {
    cerr << prog << ": Spawned only "<<d.ntasks<<" of "<<d.nreq<<"\n";
    cerr << "  Error codes of failed spawns are:\n";
    for(i=0; i<d.nreq; i++) {
      cerr << "    slave "; cerr.width(3); 
      cerr << i << ": " << d.tid[i] << "\n";
    }
  }
  else {
    cerr << prog << ": Spawned " << d.nreq << " slave processes...\n";
  }
  
  return 0;
}
Ejemplo n.º 12
0
int main(int argc, char *argv[]){
  int mytid, tids[MAXNODES];
  int numt, n, nproc, msgtype;
  double val, work, result;
  double xs[10000];
  double ys[10000][10000];
  for(int i=0; i<10000; i++){
    xs[i] = rand();
    for(int j=0; i<10000; j++){
      ys[i][j] = rand();
    }
  }
  mytid = pvm_mytid();
  nproc=4;
  numt = pvm_spawn(CLIENTNAME, NULL, PvmTaskDefault, NULL, nproc, tids);
  if (numt != nproc){
    fprintf(stderr, "numt = %d, nproc = %d\n", numt, nproc);
    fprintf(stderr, "error: pvm_spawn()\n");
    pvm_exit();
    exit(1);
  }
  msgtype=11;
  for(n=0; n<nproc; n++){
    pvm_initsend(PvmDataDefault);
    pvm_pkint(&n, 1, 1);
    pvm_pkdouble(&xs, 10000, 1);
    pvm_pkdouble(&ys, 10000, 1);
    pvm_send(tids[n], msgtype);
  }
  msgtype=22; result=0.0;
  for(n=0; n<nproc; n++){
    pvm_recv(-1, msgtype);
    pvm_upkdouble(&work, 1, 1);
    result += work;
  }
  printf("Result = %25.15lf\n", result);
  return 0;
}
Ejemplo n.º 13
0
value
Pvm_spawn_native(value task, value argv, value flag, value host,
		  value ntasks, value tids)
{
  char **cargv;
  unsigned i;
  int numt;
  unsigned cntasks = Int_val(ntasks);
  int *ctids;
  char *chost;

  cargv = malloc((Wosize_val(argv)+1)*sizeof(char*));
  ctids = malloc(cntasks*sizeof(int));
  for(i = 0; i < Wosize_val(argv); i++) cargv[i] = String_val(Field(argv, i));
  cargv[Wosize_val(argv)] = NULL;

  chost = (string_length(host) == 0 ? NULL : String_val(host));
  numt = pvm_spawn(String_val(task), cargv, Int_val(flag),chost,cntasks,ctids);
  if (numt<0) {free(cargv); free(ctids);TreatError(numt);}

  for(i = 0; i < cntasks; i++) modify(&Field(tids, i), Val_int(ctids[i]));
  free(cargv); free(ctids);
  return Val_int(numt);
}
Ejemplo n.º 14
0
void pvmica(doublereal *data, doublereal *weights, doublereal *sphere, doublereal *eigv, integer chans, integer ncomps, integer frames, integer epochs, int *window, doublereal *bias, integer *signs, char **fnames) {
	struct pvmhostinfo *hinfo;
	int                 i, j, datasize, maxep, maxfr, segs, speed, spwnd = 0, id = 0;
	int                *tids, tid, nhost, narch, nproc = 0, ntask = 0, last = 0;
	char               *name;
	FILE               *fids[3];
	integer           **srec;
	doublereal        **wrec, **brec, *basedata, *windata, *prjdata, deflr = lrate;
	tresult             result;
	tassign             assign;

/*	pvm_catchout(stdout);*/
	pvm_config(&nhost,&narch,&hinfo);
	for (i=0 ; i<nhost ; i++) nproc += speed2proc(hinfo[i].hi_speed);

	basedata = (doublereal*)malloc(ncomps*epochs*window[BASELINE]*sizeof(doublereal));
	baseline(data,basedata,ncomps,frames,epochs,window);
	runica(basedata,weights,ncomps,1,window[BASELINE]*epochs,bias,signs);
	free(basedata);

	assign.weights = weights;
	assign.chans = ncomps;
	assign.frames = window[FRAMEWINDOW];
	assign.epochs = window[EPOCHWINDOW];
	assign.bias = (int)(bias!=NULL);
	assign.signs = (int)(signs!=NULL);
	assign.extended = extended;
	assign.extblocks = extblocks;
	assign.pdfsize = pdfsize;
	assign.nsub = nsub;
	assign.verbose = verbose;
	assign.block = block;
	assign.maxsteps = maxsteps;
	assign.lrate = deflr;
	assign.annealstep = annealstep;
	assign.annealdeg = annealdeg;
	assign.nochange = nochange;
	assign.momentum = momentum;
	
	datasize = window[FRAMEWINDOW] * window[EPOCHWINDOW] * ncomps;
	windata = (doublereal*)malloc(datasize*sizeof(doublereal));
	prjdata = (doublereal*)malloc(datasize*sizeof(doublereal));
	
	maxep = (epochs-window[EPOCHWINDOW])/window[EPOCHSTEP] + 1;
	maxfr = (frames-window[FRAMEWINDOW])/window[FRAMESTEP] + 1;
	segs = maxep*maxfr;

	if (segs > nproc) {
		tids = (int*)malloc(nproc*sizeof(int));
		for (i=0 ; i<nhost ; i++) {
			name = hinfo[i].hi_name;
			speed = hinfo[i].hi_speed;
			spwnd = pvm_spawn(SPAWN_ICA,NULL,1,name,speed2proc(speed),&tids[ntask]);
			if (spwnd <= 0) error("Failed to spawn processes");
			ntask += spwnd;
		}
	}
	else {
		tids = (int*)malloc(segs*sizeof(int));
		spwnd += pvm_spawn(SPAWN_ICA,NULL,0,"",segs,tids);
		if (spwnd <= 0) error("Failed to spawn processes");
		ntask += spwnd;
	}

	for (i=0,j=0 ; i<ntask ; i++,j+=2,id++) {
		if (j >= ntask) j=1;
		assign.id   = id;
		assign.data = extract(data,windata,(int)ncomps,(int)frames,(int)epochs,(int)id,window);
		send_assign(tids[j],&assign);
	}

	wrec = (doublereal**)malloc(segs*sizeof(doublereal*));
	brec = (doublereal**)malloc(segs*sizeof(doublereal*));
	srec = (integer**)malloc(segs*sizeof(integer*));
	for (i=0 ; i<segs ; i++) {
		wrec[i] = NULL;
		brec[i] = NULL;
		srec[i] = NULL;
	}

	for (i=0 ; i<3 ; i++) fids[i] = NULL;
	if (fnames[0] != NULL) fids[0] = fopen(fnames[0],"wb");
	if (fnames[1] != NULL) fids[1] = fopen(fnames[1],"wb");
	if (fnames[2] != NULL) fids[2] = fopen(fnames[2],"wt");

	for (i=0 ; i<segs ; i++) {
		tid = receive_result(&result);
		
		printf("Received id %d\n",result.id);
		wrec[result.id] = result.weights;
		brec[result.id] = result.bias;
		srec[result.id] = result.signs;

		if (ntask < segs) {
			assign.id = id;
			assign.data = extract(data,windata,(int)ncomps,(int)frames,(int)epochs,(int)id,window);
			send_assign(tid,&assign);
			ntask++;
			id++;
		}
		else {
			send_kill(tid);
		}

		datasize = window[FRAMEWINDOW] * window[EPOCHWINDOW];
		extract(data,windata,(int)ncomps,(int)frames,(int)epochs,(int)result.id,window);
		geproj(windata,result.weights,(integer)ncomps,(integer)datasize,prjdata);
		if (eigv)
			varsort(prjdata,result.weights,sphere,&eigv[chans*(chans-ncomps)],result.bias,result.signs,(integer)ncomps,(integer)datasize,(integer)chans);
		else
			varsort(prjdata,result.weights,sphere,NULL,result.bias,result.signs,(integer)ncomps,(integer)datasize,(integer)chans);

		while (last<segs && wrec[last]!=NULL) {
			if (fids[0]!=NULL && wrec[last]!=NULL) fbc_matwrite(fids[0],chans*ncomps,wrec[last]);
			if (fids[1]!=NULL && brec[last]!=NULL) fbc_matwrite(fids[1],ncomps,brec[last]);
			if (fids[2]!=NULL && srec[last]!=NULL) iac_matwrite(fids[2],ncomps,srec[last]);
			if (wrec[last] != NULL) free(wrec[last]);
			if (brec[last] != NULL) free(brec[last]);
			if (srec[last] != NULL) free(srec[last]);
			last++;
		}
	}

	for (i=0 ; i<3 ; i++) 
		if (fids[i] != NULL) fclose(fids[i]);

	if (wrec != NULL) free(wrec);
	if (brec != NULL) free(brec);
	if (srec != NULL) free(srec);
	if (windata != NULL) free(windata);
	if (prjdata != NULL) free(prjdata);
	if (tids != NULL)    free(tids);
}
Ejemplo n.º 15
0
int main(int argc, char ** argv){
    TAILQ_INIT(&head);
    int nproc, numt, i, nhost, narch;
    int num_tasks = 0;
    struct pvmhostinfo *hostp;
    struct stat s;
    FILE * codefile = fopen("./codes", "w");

    if(argc != 2){
        exit_prog("USAGE: ./taskgen directory\n",1);
    }
    else {
        stat(argv[1], &s);
        if(s.st_mode & S_IFDIR){
            char path[PATH_MAX+1];
            realpath(argv[1],path);
            printf("Loading graphs from %s...", path);
            fflush(stdout);
            load_graph_dir(path, &num_tasks);
            printf("done. Found %d tasks.\n", num_tasks);
        }
        else{
            printf("%s is not a directory. Please check arguments.\n", argv[1]);
            exit_prog(NULL, 1);
        }
    }

    pvm_config(&nhost, &narch, &hostp);                         /*Set number of slaves to start */
    nproc = nhost * 3;                                          /*3 processes per host */

    printf("Spawning %d worker tasks on %d machines...", nproc, nhost);

    int tids[nproc];                                            /*hold the task ids of the workers */

    int flags = PvmTaskDefault;
   // flags += PvmTaskDebug;

    numt =pvm_spawn("worker", (char**)0, flags, "", nproc, tids);   /*start up the workers */

    if(numt < nproc){                                           /*Error Checking */
        printf("\n Trouble spawing slaves. 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]);
        }
        exit_prog("Failure.\n",1);
    }
    printf("done. Connected.\n");
    
    /* Main loop */
    int bufid, bytes, msgtype, source;
    int sent_tasks, comp_tasks, found_codes = 0;
    int finished = 0;
    int percent_comp = 0;
    char * buf;
    while(!finished){    
        bufid = pvm_recv(-1, -1);                               /*Accept any message from any task BLOCKING CALL*/
        pvm_bufinfo(bufid, &bytes, &msgtype, &source);
        switch(msgtype){
            case MSGREQTASK:
                if(!TAILQ_EMPTY(&head)){
                    send_task(source);                              /*send out the message */
                    sent_tasks++;
                }
                break;
            case MSGCODE:
                buf = malloc(bytes);
                pvm_upkstr(buf);
                fprintf(codefile, "%s\n", buf);
                fflush(codefile);
                comp_tasks++;
                found_codes++;
                break;
            case MSGNOCODE:
                comp_tasks++;
                break;
            default:
                printf("Incorrect MSGTYPE received from task %d. Received: %d\n", source, msgtype);
                break;
            }
        
        if(((float)comp_tasks/num_tasks * 100) > percent_comp + 1){
                printf("Tasks Complete: %d    Tasks Sent: %d    Percent Complete: %.2f\n", 
                comp_tasks, sent_tasks, (float)comp_tasks/num_tasks * 100);
                percent_comp = (float)comp_tasks/num_tasks * 100;
        }
    
        if(comp_tasks == num_tasks){
            finished = 1;
        }
        
    }
 
    printf("All tasks complete.\n");

    exit_prog(NULL, 0);
    return 0;
}
Ejemplo n.º 16
0
int main (int argc, char **argv)
  
{
	int nt;                 /* number of time samples */
	int nz;                 /* number of migrated depth samples */
	int nx,nxshot;      /* number of midpoints,shotgathers, the folds in a shot
				gather */

	int flag=1;		/*flag to use ft or meter as the unit*/
	int dip=65;		/*maximum dip angle to migrate*/
	int iz,iw,ix,it,oldsx;     /* loop counters*/
	int ntfft;        /* fft size*/
	int nw;              /* number of wave numbers */
	int mytid,tids[NNTASKS],msgtype,rc,i;/*variable for PVM function*/
	int nw1,task; 	
	int lpad=9999,rpad=9999;	/*zero-traces padded on left and right sides*/
	float f1,f2,f3,f4;	/*frequencies to build the Hamming window*/
	int nf1,nf2,nf3,nf4;	/*the index for above frequencies*/
	int NTASKS=0;		/*number of slave tasks to start*/
	char cpu_name[NNTASKS][80];	/*strings to store the computers' name*/
	int flag_cpu=0;			/*flag to control if using NTASKS variable*/

	float sx,gxmin,gxmax;	/*location of  geophone and receivers*/
	int isx,nxo,ifx=0;	/*index for geophone and receivers*/
	int ix1,ix2,ix3,il,ir;	/*dummy index*/

	float *wl,*wtmp;	/*pointers for the souce function*/
	float Fmax=25;		/*peak frequency to make the Ricker wavelet*/
	int ntw,truenw;		/*number of frequencies to be migrated*/


	float dt=0.004,dz;   	/*time, depth sampling interval*/
	float ft;            	/*first time sample*/
	float dw;         	/*frequency sampling interval*/
	float fw;         	/*first frequency*/
	float dx;            	/*spatial sampling interval*/
	float **p,**cresult,**result_tmp;    /* input, output data*/
	float **v;		/*double pointer direct to velocity structure*/ 
	complex *wlsp,**cp,**cq,**cq1; /*pointers for internal usage*/

	char *vfile="";         /* name of file containing velocities */
	char *cpufile="";	/* name of file containing CPU name */

	FILE *vfp,*cpu_fp;

                        
	/* hook up getpar to handle the parameters */
	initargs(argc,argv);
	requestdoc(1);

	/* get optional parameters */
	if (!getparfloat("ft",&ft)) ft = 0.0;
	if (!getparint("nz",&nz)) err("nz must be specified");
	if (!getparfloat("dz",&dz)) err("dz must be specified");
	if (!getparstring("vfile", &vfile)) err("vfile must be specified");
	if (!getparint("nxo",&nxo)) err("nxo must be specified");
	if (!getparint("nxshot",&nxshot)) err("nshot must be specified");
	if (!getparfloat("Fmax",&Fmax)) err("Fmax must be specified");
	if (!getparfloat("f1",&f1)) f1 = 10.0;
	if (!getparfloat("f2",&f2)) f2 = 20.0;
	if (!getparfloat("f3",&f3)) f3 = 40.0;
	if (!getparfloat("f4",&f4)) f4 = 50.0;
	if (!getparint("lpad",&lpad)) lpad=9999;
	if (!getparint("rpad",&rpad)) rpad=9999;
	if (!getparint("flag",&flag)) flag=1;
	if (!getparint("dip",&dip)) dip=65;

	if (getparstring("cpufile", &cpufile)){
	cpu_fp=fopen(cpufile,"r");
	NTASKS=0;
	while(!feof(cpu_fp)){
	fscanf(cpu_fp,"%s",cpu_name[NTASKS]);
	NTASKS++;
	}
	NTASKS-=1;
	flag_cpu=1;
	}
	else /*if cpufile not specified, the use NTASKS*/
	if (!getparint("NTASKS",&NTASKS)) err("No CPUfile specified, NTASKS must be specified");

	/*allocate space for the velocity profile*/
	tshot=nxshot;
	v=alloc2float(nxo,nz);
        
	/*load velicoty file*/
	vfp=efopen(vfile,"r");
	efread(v[0],FSIZE,nz*nxo,vfp);
	efclose(vfp);

	/*PVM communication starts here*/
	mytid=pvm_mytid();	/*get my pid*/
	task=NTASKS;
	warn("\n %d",task);
	rc=0;
	/*spawn slave processes here*/
	if(!flag_cpu){
	rc=pvm_spawn(child,NULL,PvmTaskDefault,"",task,tids);
	}
	else{
	for(i=0;i<NTASKS;i++){
	rc+=pvm_spawn(child,NULL,PvmTaskHost,cpu_name[i],1,&tids[i]);
	}
	}
        
	/*show the pid of slaves if*/
	for(i=0;i<NTASKS;i++){
	if(tids[i]<0)warn("\n %d",tids[i]);
	else warn("\nt%x\t",tids[i]);
        }

	/*if not all the slaves start, then quit*/
	if(rc<NTASKS){ warn("error");pvm_exit();exit(1);}
        
	/*broadcast the global parameters nxo,nz,dip to all slaves*/
	pvm_initsend(PvmDataDefault);
	rc=pvm_pkint(&nxo,1,1);
	rc=pvm_pkint(&nz,1,1);
	rc=pvm_pkint(&dip,1,1);
	msgtype=PARA_MSGTYPE;
	task=NTASKS;
	rc=pvm_mcast(tids,task,msgtype);

	/*broadcast the velocity profile to all slaves*/
        pvm_initsend(PvmDataDefault);
        rc=pvm_pkfloat(v[0],nxo*nz,1);
        msgtype=VEL_MSGTYPE; 
        rc=pvm_mcast(tids,task,msgtype);
	
	/*free the space for velocity profile*/
	free2float(v);


/*loop over shot gathers begin here*/
loop:

        /* get info from first trace */
        if (!gettr(&tr))  err("can't get first trace");
        nt = tr.ns;


        /* let user give dt and/or dx from command line */
        if (!getparfloat("dt", &dt)) {
                if (tr.dt) { /* is dt field set? */
                        dt = ((double) tr.dt)/1000000.0;
                } else { /* dt not set, assume 4 ms */   
                        dt = 0.004;
                        warn("tr.dt not set, assuming dt=0.004");
                }
        }
        if (!getparfloat("dx",&dx)) {
                if (tr.d2) { /* is d2 field set? */
                        dx = tr.d2;
                } else {
                        dx = 1.0;
                        warn("tr.d2 not set, assuming d2=1.0");
                }
        }


	sx=tr.sx;
	isx=sx/dx;
	gxmin=gxmax=tr.gx;
	oldsx=sx;

        /* determine frequency sampling interval*/
        ntfft = npfar(nt);
        nw = ntfft/2+1;
        dw = 2.0*PI/(ntfft*dt);

	/*compute the index of the frequency to be migrated*/
	fw=2.0*PI*f1;
	nf1=fw/dw+0.5;

	fw=2.0*PI*f2;
	nf2=fw/dw+0.5;
 
	fw=2.0*PI*f3;
	nf3=fw/dw+0.5;

	fw=2.0*PI*f4;
	nf4=fw/dw+0.5;

	/*the number of frequency to migrated*/
	truenw=nf4-nf1+1;
	fw=0.0+nf1*dw;
	warn("nf1=%d nf2=%d nf3=%d nf4=%d nw=%d",nf1,nf2,nf3,nf4,truenw);
	fw=0.0;

        /* allocate space */
        wl=alloc1float(ntfft);
        wlsp=alloc1complex(nw);

	/*generate the Ricker wavelet*/
        wtmp=ricker(Fmax,dt,&ntw);

        for(it=0;it<ntfft;it++)
        wl[it]=0.0;

        for(it=0;it<ntw-12;it++)
        wl[it]=wtmp[it+12];
	free1float( wtmp);

	/*Fourier transform the Ricker wavelet to frequency domain*/
        pfarc(-1,ntfft,wl,wlsp);
        
	/* allocate space */
        p = alloc2float(ntfft,nxo);
        cp = alloc2complex(nw,nxo);

        for (ix=0; ix<nxo; ix++)
                for (it=0; it<ntfft; it++)
                        p[ix][it] = 0.0;
       
	
	/*read in a single shot gather*/
	ix=tr.gx/dx;
	memcpy( (void *) p[ix], (const void *) tr.data,nt*FSIZE);

        nx = 0;

	while(gettr(&tr)){
			int igx;

			if(tr.sx!=oldsx){ fseek(stdin,(long)(-240-nt*4),SEEK_CUR); break;}
			igx=tr.gx/dx;
			memcpy( (void *) p[igx], (const void *) tr.data,nt*FSIZE);  
                
			if(gxmin>tr.gx)gxmin=tr.gx;
			if(gxmax<tr.gx)gxmax=tr.gx;
			nx++;
			oldsx=tr.sx;
			}

	warn("\nnx= %d",nx);
	warn("sx %f , gxmin %f  gxmax %f",sx,gxmin,gxmax);

	/*transform the shot gather from time to frequency domain*/
        pfa2rc(1,1,ntfft,nxo,p[0],cp[0]);

	/*compute the most left and right index for the migrated section*/ 
	ix1=sx/dx;
	ix2=gxmin/dx;
	ix3=gxmax/dx;
        
	if(ix1>=ix3)ix3=ix1;
	if(ix1<=ix2)ix2=ix1;

	il=ix2;
	ir=ix3;
	ix2-=lpad;
	ix3+=rpad;
	if(ix2<0)ix2=0;
	if(ix3>nxo-1)ix3=nxo-1;

	/*the total traces to be migrated*/
	nx=ix3-ix2+1;

	/*allocate space*/
        cq = alloc2complex(nx,nw);
	cq1 = alloc2complex(nx,nw);


	/*transpose the frequency domain data from data[ix][iw] to data[iw][ix] and
	apply a Hamming at the same time*/

	for (ix=0; ix<nx; ix++)
	for (iw=0; iw<nw; iw++){	

	float tmpp=0.0,tmppp=0.0;
	
	if(iw<nf1||iw>nf4)
	cq[iw][ix]=cmplx(0.0,0.0);
	else{
		if(iw>=nf1&&iw<=nf2){tmpp=PI/(nf2-nf1);tmppp=tmpp*(iw-nf1)-PI;tmpp=0.54+0.46*cos(tmppp);
		cq[iw][ix]=crmul(cp[ix+ix2][iw],tmpp);}
		else{
			if(iw>=nf3&&iw<=nf4){tmpp=PI/(nf4-nf3);tmppp=tmpp*(iw-nf3);tmpp=0.54+0.46*cos(tmppp);
			cq[iw][ix]=crmul(cp[ix+ix2][iw],tmpp);}
			else
			{cq[iw][ix]=cp[ix+ix2][iw];}
		}
	}
	cq[iw][ix]=cp[ix+ix2][iw];
	cq1[iw][ix]=cmplx(0.0,0.0);
	}


	ix=sx/dx-ifx;
	warn("ix %d",ix);

	for(iw=0;iw<nw;iw++){
	cq1[iw][ix-ix2]=wlsp[iw];
	}


	free2float(p);
	free2complex(cp);
	free1float(wl);
	free1complex(wlsp);

	/*if the horizontal spacing interval is in feet, convert it to meter*/ 
	if(!flag)
	dx*=0.3048;

	/*start of the timing function*/
	time(&t1);

	/* send local parameters to all slaves*/
	pvm_initsend(PvmDataDefault);

	ix=15;
	rc=pvm_pkint(&ix,1,1);

	rc=pvm_pkint(&ntfft,1,1);
        rc=pvm_pkint(&ix2,1,1);
        rc=pvm_pkint(&ix3,1,1);
	rc=pvm_pkint(&isx,1,1);
	rc=pvm_pkint(&il,1,1);
	rc=pvm_pkint(&ir,1,1);
        rc=pvm_pkfloat(&dx,1,1);
        rc=pvm_pkfloat(&dz,1,1);
        rc=pvm_pkfloat(&dw,1,1);
	rc=pvm_pkfloat(&dt,1,1);
	msgtype=PARA_MSGTYPE;

	task=NTASKS;
	rc=pvm_mcast(tids,task,msgtype);

	
	/* send all the frequency to slaves*/
	count=NTASKS*5; /*count is the number of frequency components in a shot
			gather*/ 
        
	nw=truenw;        
	nw1=nw/(count);
	if(nw1==0)nw1=1;
	total=count=ceil(nw*1.0/nw1);

	/* if it is the first shot gather, send equal data to all the slaves, then for
	the following shot gathers, only send data when slave requests*/

	if(nxshot==tshot){

	for(i=0;i<NTASKS;i++){ 
	float *tmpp;
	float fw1;
	int nww,byte,nwww;
			
        pvm_initsend(PvmDataDefault);
	nww=nf1+i*nw1;fw1=fw+nww*dw;
	nwww=nw1;
        byte=UnDone;

        rc=pvm_pkint(&byte,1,1);
        rc=pvm_pkfloat(&fw1,1,1);
        rc=pvm_pkint(&nwww,1,1);   
	rc=pvm_pkfloat((float *)cq[nww],nx*nwww*2,1);
        rc=pvm_pkfloat((float *)cq1[nww],nx*nwww*2,1);
	msgtype=DATA_MSGTYPE;
	pvm_send(tids[i],msgtype);
	}

	count-=NTASKS;

	}


	while(count){

	int tid0,bufid;
	float *tmpp;
	float fw1;
	int nww,byte,nwww;  
	int i;  
	i=total-count;

        
	msgtype=COM_MSGTYPE;
	bufid=pvm_recv(-1,msgtype);
	rc=pvm_upkint(&tid0,1,1);
	pvm_freebuf(bufid);
        
        pvm_initsend(PvmDataDefault);
        nww=nf1+i*nw1;fw1=fw+nww*dw;
        if(i==total-1)nwww=nw-nw1*i;
        else nwww=nw1;

	byte=UnDone;
        rc=pvm_pkint(&byte,1,1);
        rc=pvm_pkfloat(&fw1,1,1);
        rc=pvm_pkint(&nwww,1,1);
        rc=pvm_pkfloat((float *)cq[nww],nx*nwww*2,1);
        rc=pvm_pkfloat((float *)cq1[nww],nx*nwww*2,1);
        msgtype=DATA_MSGTYPE;
        pvm_send(tid0,msgtype);

        count--;
	}

	ix=Done;
        
        pvm_initsend(PvmDataDefault);
        rc=pvm_pkint(&ix,1,1);

        msgtype=DATA_MSGTYPE;
        pvm_mcast(tids,task,msgtype);


	free2complex(cq);
	free2complex(cq1);

	time(&t2);

	warn("\n %d shot been finished in %f seconds, Ntask=%d",nxshot,difftime(t2,t1),NTASKS);

	nxshot--;                       

	if(nxshot)goto loop;
	

	/*when all the shot gathers done, send signal to all slaves to request the
								partial imaging*/
	ix=FinalDone;
        pvm_initsend(PvmDataDefault);
        rc=pvm_pkint(&ix,1,1);
        msgtype=PARA_MSGTYPE;
        pvm_mcast(tids,task,msgtype);
        
	/*allocate space for the final image*/
        cresult = alloc2float(nz,nxo);
	for(ix=0;ix<nxo;ix++)
        for(iz=0;iz<nz;iz++)
        { cresult[ix][iz]=0.0;
	}

	result_tmp= alloc2float(nz,nxo);
	
	/*receive partial image from all the slaves*/
	msgtype=RESULT_MSGTYPE;
	i=0;

	while(i<NTASKS){
	int bufid;
	bufid=pvm_recv(-1,msgtype);
	rc=pvm_upkfloat(result_tmp[0],nxo*nz,1);
	pvm_freebuf(bufid);
	for(ix=0;ix<nxo;ix++)
	for(iz=0;iz<nz;iz++)
	{
	cresult[ix][iz]+=result_tmp[ix][iz];	
	}
	i=i+1;
	warn("\n i=%d been received",i);
	}

	/*send signal to all slaves to kill themselves*/
	pvm_initsend(PvmDataDefault);
	pvm_mcast(tids,task,COM_MSGTYPE);

	/*output the final image*/
        for(ix=0; ix<nxo; ix++){
                tr.ns = nz ;
                tr.dt = dz*1000000.0 ;
		tr.d2 = dx;
		tr.offset = 0;
		tr.cdp = tr.tracl = ix;
                memcpy( (void *) tr.data, (const void *) cresult[ix],nz*FSIZE);
                puttr(&tr);
        }



        pvm_exit();            
        return EXIT_SUCCESS;
                                
}                               
Ejemplo n.º 17
0
int
main(int argc, char **argv)
{
    int tid;
    int parent;

    struct pvmhostinfo *hostp;
    int nhost, narch;

    tid = pvm_mytid();
    if(tid < 0) pvm_ferror("pvm_mytid", 1);

    parent = pvm_parent();

    if(parent == PvmNoParent || parent == PvmParentNotSet) {
        /* Processus pere */
        int nchildren, children[MAXCHILDREN];
        int i, j, res, rc;
      int bytes, tag, from_tid;


    /* Ask PVM for information about the virtual machine, and display
       it to the user. 
    */
    
        pvm_config(&nhost, &narch, &hostp);
        printf("I found the following %d hosts...\n",nhost);
		
		
        for (i = 0; i < nhost; i++)
          printf("%d. %s \t(%s)\n",i,hostp[i].hi_name,hostp[i].hi_arch);



        rc = pvm_spawn("pvm_mandel", NULL, PvmTaskDefault, NULL, 
                       NUMCHILDREN, children);
        if(rc < 0) pvm_ferror("pvm_spawn", 1);
        printf("%d enfants\n", rc);
        nchildren = 0;
        for(i = 0; i < NUMCHILDREN; i++) {
            printf("Enfant %d, tid = %d\n", i, children[i]);
            if(children[i] >= 0)
                nchildren++;
            if(nchildren < 1)
                pvm_ferror("Pas d'enfants", 0);
        }
        for(i = -MAXX; i <= MAXX; i++) {
            for(j = -MAXY; j <= MAXY; j++) {
               rc = pvm_recv(-1,-1);

              if (rc < 0) {
                printf("An error occurred when trying to receive a message.\n");
                break;
              }

      /* Find out who this message is from, and how big it is. */

               rc = pvm_bufinfo(rc,&bytes,&tag,&from_tid);

               /* printf("received message from %s of %d bytes, tag %d\n",
                  get_host_by_tid(hostp,nhost,from_tid), bytes, tag);
               */

                rc = pvm_upkint(&res, 1, 1);
                if(rc < 0) pvm_ferror("pvm_upkint", 1);
                cases[i + MAXX][j + MAXY] = res;
            }
        }
        dump_ppm("mandel.ppm", cases);
        printf("Fini.\n");
        pvm_exit();
        exit(0);
    } else if(parent >= 0) {
        /* On est l'un des fils */
        double x, y;
        int i, j, res, rc;
        printf("Fils: %d\n", tid);
        for(i = -MAXX; i <= MAXX; i++) {
            for(j = -MAXY; j <= MAXY; j++) {
                x = 2 * i / (double)MAXX;
                y = 1.5 * j / (double)MAXY;
                res = mandel(x, y);
                rc = pvm_initsend(PvmDataDefault);
                if(rc < 0) pvm_ferror("pvm_initsend", 1);
                rc = pvm_pkint(&res, 1, 1);
                if(rc < 0) pvm_ferror("pvm_pkint", 1);
                rc = pvm_send(parent, 0);
                if(rc < 0) pvm_ferror("pvm_send", 1);
            }
        }
        printf("Fils %d termine.\n", tid);
        pvm_exit();
        exit(0);
    } else
        pvm_ferror("pvm_parent", 1);

    assert(0);
}
Ejemplo n.º 18
0
/* Rank sort paralelizado*/
int main (int argc, char *argv[]){
	int tam, i, j, rank, id, tag=100, processos, retorno;
	int *numeros, *rankeados, *tids, *ranks;
	char *grupo = "grupo";

	srand(time(NULL));

	printf("Digite numero de processos a serem disparados:\n");
	scanf("%d", &processos);

	printf("Digite o tamanho do vetor a ser ordenado:\n");
	scanf("%d", &tam );

	retorno=(tam/processos);
	
	numeros=(int *) malloc (tam*sizeof(int));
	rankeados=(int*) malloc (tam*sizeof(int));
	tids=(int*) malloc (processos*sizeof(int));
	ranks=(int*)malloc ((tam)*sizeof(int));
	


	if((!numeros)||(!rankeados)||(!tids)||(!ranks))
	{
		printf("Erro na alocacao de memoria\n");
		return 1;
	}


	printf("Vetor não ordenado:\n");
	printf("Números: ");
	for(i=0;i<tam;i++)
	{
		numeros[i]=rand() % 1001;
		printf(" %d ", numeros[i] );
		
	}
	printf("\n");
		
	pvm_initsend(PvmDataDefault);
	pvm_cachout(stdout);
	id = pvm_joingroup(grupo);
	
	if(id==0)
	{
		if(pvm_spawn("tarefas", NULL, PvmTaskDefault, "", processos-1,tids)!=(processos-1))
		{
			printf("Erro: Não foi possível disparar os processos\n");
			return 2;
		}
		else
		{
			
	  		for(i=0;i<tam;i++)
	              	{
				pvm_barrier(grupo, NPROCS);
				pvm_scatter(ranks,numeros,(tam/processos),PVM_INT,tag,grupo,0);
              			rank=0;
                    			if((numeros[i]<numeros[j]) || ((numeros[i]==numeros[j])&&(j<i)))
                       			{
                               			 rank++;
					}
//
		                  rankeados[rank]=numeros[i];
	        	          printf("rank:%d ", rank);
			}
        //		pvm_barrier(grupo, NPROCS);
	
		}
			
	}

/*	for(i=0;i<tam;i++)
	{
		rank=0;
		for(j=0;j<tam;j++)
		{
			if((numeros[i]<numeros[j]) || ((numeros[i]==numeros[j])&&(j<i)))
			{
				rank++;
			}
		}
		rankeados[rank]=numeros[i];
		printf("rank:%d ", rank);
	}
*/	

	printf("Vetor ordenado:\n");
	printf("Números: ");
	for(i=0;i<tam;i++)
	{
		printf(" %d ", rankeados[i] );
		
	}
	printf("\n");

	free(numeros);
	free(rankeados);
	return 0;
}
Ejemplo n.º 19
0
// Hook up to the pvm and spawn the slave processes.
int
PVMDemeGA::spawn(const char* slavename) {
  _mid = pvm_mytid();
  if(_mid < 0) {
    cerr << "\n" << className() << ": spawn:\n";
    cerr << "  Bad ID for master task. Have you started the PVM?\n";
    return _status = _mid;
  }

  struct pvmhostinfo* hostp;
  _status = pvm_config(&_nhosts, &_narch, &hostp);
  if(_status == PvmSysErr) {
    cerr << "\n" << className() << ": spawn:\n";
    cerr << "  PVM not responding. Have you started the PVM?\n";
    return _status;
  }
  
  _Ntid = npop;
  _tid = new int [_Ntid];		// task IDs for the slaves
  char sn[32];				// PVM is not const-safe...
  strcpy(sn, slavename);
  _ntid = pvm_spawn(sn, (char**)0, 0, "", _Ntid, _tid);
  if(_ntid <= 0) {
    cerr << className() << ": spawn:\n  Error spawning slaves.\n";
    cerr << "  Error codes of failed spawns are:\n";
    for(int i=0; i<_Ntid; i++) {
      cerr << "    slave "; cerr.width(3); cerr<<i<<": "<<_tid[i]<<"\n";
    }
    pvm_exit();
    return _status = -1;
  }
  else if(_ntid < _Ntid) {
    cerr << className() << ": spawn:\n  ";
    cerr << "  Spawned only "<<_ntid<<" of "<<_Ntid<<"\n";
    cerr << "  Error codes of failed spawns are:\n";
    for(int i=0; i<_Ntid; i++) {
      if(_tid[i] < 0) {
	cerr << "    slave "; cerr.width(3); cerr<<i<<": "<<_tid[i]<<"\n";
      }
    }
  }
  else {
    cerr << className() << ": spawn:\n";
    cerr << "  Spawned " << _Ntid << " slave processes...\n";
  }

#ifdef DEBUG
  cerr << "waiting for response from slaves...\n";
#endif

  int flag = _ntid;
  while(flag > 0) {
     int bufid = pvm_recv(-1, -1);
    if(bufid >= 0) {
      int bytes, msgtag, tid;
      _status = pvm_bufinfo(bufid, &bytes, &msgtag, &tid);
      int which = tid2idx(tid);

      switch(msgtag) {
      case MSG_READY:
#ifdef DEBUG
	cerr << "  slave " << tid << " (" << which << ") is alive\n";
#endif
	flag--;
	break;

      default:
	cerr << className() << ": spawn:\n";
	cerr << "  unexpected msgtag: " << msgtag << "\n";
	break;
      }
    }
    else {
      cerr << className() << ": spawn:\n";
      cerr << "  error from pvm_recv: " << bufid << "\n";
    }
  }

#ifdef DEBUG
  cerr << "slaves appear to be up and running.\n";
#endif

  return _status;
}
Ejemplo n.º 20
0
void 
population_fitness(struct pop_c* pop_conf, struct state** population)
{

	int ntask = MAXNCHILD;
	int info;
	int mytid;
	int child[MAXNCHILD];
	int i, j;
	mytid = pvm_mytid();

	if (mytid < 0) 
	{ 
		/* the perneially informative error message of my youth. */
		pvm_perror("wat"); 
		exit(-1);
	}

	/* spawn the child tasks */
	info = pvm_spawn("/home/rwblair/projects/parallel_ga/slave", (char**)0, 
	    PvmTaskDefault, (char*)0, ntask, child);
	/* only proceeds if all children properly spawned. It doesn't have to be
	 * this way but its easiest
	 */
	printf("result of pvm_spawn call: %d\n", info);
	printf("value of first index of child array: %d\n", child[0]);
	if (info != ntask) 
	{
		pvm_exit(); 
		exit(-1);
	}
	
	int tmp;	
	for (i = 0; i < ntask; i++)
	{
		tmp = ((pop_conf->pop_size)/ntask);
		if (i < (pop_conf->pop_size % ntask))
			tmp++;
		pvm_initsend(PvmDataDefault);
		pvm_pkint(&tmp, 1, 1);
		pvm_pkint(&(pop_conf->n), 1, 1);
		info = pvm_send(child[i], 0);
	}
	
	j = 0;
	for (i = 0; i < pop_conf->pop_size; i++) 
	{
		pvm_initsend(PvmDataDefault);
		pvm_pkint(&i, 1, 1);
		pvm_pkint(population[i]->configuration, pop_conf->n, 1);

		if ((i == pop_conf->pop_size -1) || 
		    (((pop_conf->pop_size / MAXNCHILD)) * (j + 1)) - 1 == i)
		{
			info = pvm_send(child[j++], 0);
		}
	}


	int recv_ret;
	int recv_index;	
	int recv_fit;
	/* error handling, if a given thing f***s up how can it be unfucked? */
	for (i = 0; i < pop_conf->pop_size; i++)
	{
		recv_ret = pvm_recv(-1, -1);
		pvm_upkint(&recv_index, 1, 1);
		pvm_upkint(&recv_fit, 1, 1);	
		printf("recieved fitness: %d\n", recv_fit);
		population[recv_index]->fitness = recv_fit;
		/*
		if ((recv_index < 0) || (recv_index >= pop_conf->pop_size))
			printf("BAD RECV_INDEX\n");
		*/
	}

	pvm_exit();
	return;

}
Ejemplo n.º 21
0
void main (int argc, char** argv)
{
	int Message_counter ; /* counter for message packing */
	int My_tid ; /* my task id */

	/* show start up message */
	printf ("\n-=> Fractal Terrain Engine version 2.1 release 2 <=-\n\n") ;

	/* read the config files */
	read_config (argc,argv) ;

	/* set up the pixel buffer and it's variables */ 
	Pixel_buffer_width=User_view.X_size/Number_of_workers;
	Pixel_buffer_size=
		Pixel_buffer_width*User_view.Y_size*3*sizeof(unsigned char) ;
	Pixel_buffer=(unsigned char *) malloc(Pixel_buffer_size) ;

	/* set up worker tids array */
	Worker_tids=(int *)malloc(Number_of_workers*sizeof(int)) ;

	/* set up the image buffer */
	Image_buffer=(unsigned char *) malloc 
		((User_view.X_size*User_view.Y_size*3*sizeof(unsigned char))) ;

	/* start up pvm */
	if ((My_tid = pvm_mytid()) < 0) 
	{
		exit(1);
	}
	/* start up the workers */

	pvm_spawn(WORKER_NAME,(char**)0,PvmTaskDefault,"",
		Number_of_workers,Worker_tids) ;

	printf ("INFO:Spawned %i Workers\n",Number_of_workers) ;

	/* tell the worker what values to use for the terrain function */
	pvm_initsend(PvmDataDefault) ;

	pvm_pkdouble(&H,1,1) ;
	pvm_pkdouble(&Lacunarity,1,1);
	pvm_pkdouble(&Octaves,1,1);
	pvm_pkdouble(&Offset,1,1) ;

	pvm_pkfloat(&Ambient_light,1,1) ;

	pvm_pkfloat(&Fog.Red,1,1) ;
	pvm_pkfloat(&Fog.Green,1,1);
	pvm_pkfloat(&Fog.Blue,1,1) ;

	pvm_pkfloat(&Sky.Red,1,1) ;
	pvm_pkfloat(&Sky.Green,1,1) ;
	pvm_pkfloat(&Sky.Blue,1,1) ;

	pvm_pkfloat(&Horizon.Red,1,1) ;
	pvm_pkfloat(&Horizon.Green,1,1) ;
	pvm_pkfloat(&Horizon.Blue,1,1) ;

	pvm_pkdouble(Colour_boundaries,NUMBER_OF_TERRAIN_COLOURS,1) ;

	for ( Message_counter = 0 ;
		Message_counter<NUMBER_OF_TERRAIN_COLOURS ;
		Message_counter++ )
	{
		pvm_pkfloat(&Terrain_colours[Message_counter].Red,1,1) ;
		pvm_pkfloat(&Terrain_colours[Message_counter].Green,1,1) ;
		pvm_pkfloat(&Terrain_colours[Message_counter].Blue,1,1) ;
	}

	pvm_pkdouble(&Fog_start,1,1) ;
	pvm_pkdouble(&Fog_end,1,1) ;

	/* tell the worker what values to use for the display */
	pvm_pkdouble(&Ray_step,1,1) ;
	pvm_pkdouble(&X_view_angle,1,1) ; 
	pvm_pkdouble(&Y_view_angle,1,1) ;
	pvm_pkint(&Pixel_buffer_width,1,1) ;
	pvm_pkint(&User_view.Y_size,1,1) ;
	pvm_pkdouble(&X_ray_angle,1,1) ;
	pvm_pkdouble(&Y_ray_angle,1,1) ;

	/* send the message to all the workers */
	pvm_mcast (Worker_tids,Number_of_workers,INFO) ;

	/* set up light source */
	normalize_3d(Light_source) ;

	/* set the light source */
	Light_source[0]=0.1 ;
	Light_source[1]=0.4 ;
	Light_source[2]=0.3 ;

	/* tell the worker what values to use for the light source */
	pvm_initsend(PvmDataDefault) ;
	pvm_pkdouble(Light_source,3,1) ;
	pvm_mcast (Worker_tids,Number_of_workers,NEW_LIGHT_SOURCE) ;

	/* set up the users view point */
	Height=1.0 ;
	User.X=0 ;
	User.Y=0 ;
	User.Z=Height ;
	User.X_angle=0.0 ;
	User.Y_angle=0.0 ;
	User.Z_angle=0.0 ;

	/* set up window */
	open_window() ;
	print_keys() ;

	/*									*/
	/* set up the keyboard,Reshape and display routines			*/
	/*									*/
	auxKeyFunc(AUX_Q,kill_workers) ;
	auxKeyFunc(AUX_q,kill_workers) ;
	auxKeyFunc(AUX_ESCAPE,kill_workers) ;   

	auxKeyFunc(AUX_LEFT,left) ;
	auxKeyFunc(AUX_RIGHT,right) ;
	auxKeyFunc(AUX_UP,forwards) ;
	auxKeyFunc(AUX_DOWN,backwards) ;
	auxKeyFunc(AUX_a,up) ;
	auxKeyFunc(AUX_A,up) ;
	auxKeyFunc(AUX_Z,down) ;
	auxKeyFunc(AUX_z,down) ;

	auxKeyFunc(AUX_J,save_image) ;
	auxKeyFunc(AUX_j,save_image) ;

	auxMainLoop(display_loop) ;

}
Ejemplo n.º 22
0
int main(int argc, char **argv)
{
  int myTID;

  int tids[NPROC] = {[0 ... NPROC-1] = 0};
  int res;

  myTID = pvm_mytid();
  printf("Master: TID is %d\n", myTID);

  double          a;
  double          b;
  int          num_points;
  a = atof(argv[1]);
  b = atof(argv[2]);
  num_points = atoi(argv[3]);

  double begins[NPROC];
  double ends[NPROC];

  double basic_range = (b-a)/NPROC;
  //double extra_range = fmod((b-a),NPROC);

  for (int procindex = 0; procindex < NPROC; procindex++) {
    begins[procindex] = procindex * basic_range;
    ends[procindex] = begins[procindex] + basic_range;

    printf("begins[%d]= %f ends[%d]= %f\n", procindex,begins[procindex], procindex,ends[procindex]);
  }

  printf ("basic_range = %f\n", basic_range);
  

  res = pvm_spawn("slave", NULL, PvmTaskDefault, "", NPROC, tids);
  printf("res %d\n", res);
  if (res<1) {
    printf("Master: pvm_spawn error\n");
    pvm_exit();
    exit(1);
  }
  //for (int procindex = 0; procindex < NPROC; procindex++) printf("tids[%d] = %d\n", procindex, tids[procindex]);

  for (int procindex = 0; procindex < NPROC; procindex++) {
    pvm_initsend(PvmDataDefault);
    pvm_pkdouble(&begins[procindex], 1, 1);
    pvm_pkdouble(&ends[procindex], 1, 1);
    pvm_pkint(&num_points, 1, 1);

    pvm_send(tids[procindex], 1);
  }

  double result=0;
  for (int procindex = 0; procindex < NPROC; procindex++) {
    double r=0;
    pvm_recv(-1, -1);
    pvm_upkdouble(&r, 1, 1);

    printf("Master has received r=%f\n", r);
    result += r;
  }
  printf("Result %f\n", result);

  pvm_exit();

  return 0;
}
Ejemplo n.º 23
0
int main(int argc, char* argv[])
{
  // Timeout for Message Receive
  struct timeval tmout;
  tmout.tv_usec=100;
  tmout.tv_sec=0;
  
  // Size for Data Packets  
  int data_size;

  // Numer of running tasks
  int curcount;

  // Check if all data sent
  bool finished;

  // TID of host to send data
  int slave_tid;

  // Data Buffer for outgoing messages
  int buff;

  // Read the frequency list
  read_freq_list(FREQ_LIST_FILE);

  // Total number of Data Elements
  int data_count=freq_count;

  // Current possition in the array
  int current_data=0;

  // Store master-id in PVM
  {
    int master_id=pvm_mytid();
    pvm_delete((char *) "master",0);
    pvm_insert((char *)"master",0,master_id);
    // Parameters for Spawn
    char *params[2]={(char *) "1", NULL};
    char *slave=(char *) "matcher_slave";
    int tids[HOST_COUNT];
    int spawncount=pvm_spawn(slave,params,PvmTaskDefault,NULL,HOST_COUNT,tids);
  }

  // Get number of current tasks
  pvm_tasks(0,&curcount,NULL);
  
  finished=false;
  do
    {
      // Check for error
      if (pvm_probe(-1,MSG_SLAVE_ERROR))
	{
	  char error[32];
	  int err_no=0;
	  pvm_recv(-1,MSG_SLAVE_ERROR);
	  pvm_upkint(&slave_tid,1,1);
	  pvm_upkint(&err_no,1,1);
	  printf("Fehler in Slave %d Code %d\n",slave_tid,err_no);
	}
      // Send Data or End-Of-Data
      else if(pvm_trecv(-1,MSG_SLAVE_READY,&tmout)>0)
	{
	  pvm_upkint(&slave_tid,1,1);		
	  // No more data
	  if (finished)
	    {
	      pvm_initsend(PvmDataDefault);
	      pvm_send(slave_tid,MSG_MASTER_EOD);
	    }
	  // Send data packet
	  else
	    {
	      buff=pvm_initsend(PvmDataDefault);

	      if (data_count>=PACK_SIZE)
		data_size=PACK_SIZE;
	      else
		data_size=data_count;
	      data_count-=data_size;
	      pvm_pkint(&data_size,1,1);
	      for(int ct=0;ct<data_size;ct++)
		{
		  // Store the data in the buffer
		  if (current_data<=freq_count)
		    {
		      pvm_pkstr(freq_list[current_data]->word.getValue());
		      pvm_pkulong(&(freq_list[current_data]->count),1,1);
		      current_data++;
		    }
		}
	      pvm_initsend(PvmDataDefault);
	      pvm_send(slave_tid,MSG_MASTER_DATA);
	      printf("Send %d sets of %d to %d\n",data_size,data_count,slave_tid);
	      if (data_count==0) 
		finished=true;
	    }
	}
      // Receive Result
      else if (pvm_probe(-1,MSG_SLAVE_RESULT))
	{
	  if (pvm_trecv(-1,MSG_SLAVE_RESULT,&tmout)>0)
	    {
	      pvm_upkint(&slave_tid,1,1);
	      // Number of elements
	      pvm_upkint(&data_size,1,1);	    
	      for (int ct=0;ct<data_size;ct++)
		{
		  unsigned long res1=0;
		  unsigned long res2=0;
		  // Read the result data
		  /* to fill */
		  // pvm_upkulong(&res1,1,1);
		  // pvm_upkulong(&res2,1,1);
		  // printf("Result %llu\n",(unsigned long long int)res2*ULONG_MAX+res1);
		}
	      PvmDataDefault
	      pvm_send(slave_tid,MSG_MASTER_EXIT);
	    }
	}
      pvm_tasks(0,&curcount,NULL);
    }
  while(curcount>2);
  pvm_exit();
  return 0;
}
Ejemplo n.º 24
0
int main (int argc, char* argv[])
{
	if(argc !=4)
	{
		printf("usage : ./craquage p r m\n");
		return EXIT_FAILURE;
	}
	
	//Initialisation des variables
	int nb_esclaves = atoi(argv[1]);
	int* tids = (int*) calloc(nb_esclaves, sizeof(int));
	int longueur_mdp = atoi(argv[2]);
	char* mdp = (char*) calloc(strlen(argv[3])+1, sizeof(char));
	strcpy(mdp, argv[3]);

	//declaration de type de tres long entiers (avec bibliotheque GMP)
	mpz_t debut_sequence, pas_reel, pas, fin_exec;
	mpz_init(debut_sequence);
	mpz_init(pas_reel);
	mpz_init(pas);
	mpz_init(fin_exec);

	//recuperation du chemin de l executable
	char* chemin = getcwd(NULL, 1000);
	strcat(chemin, "/craquage_esclave");

	//creation des arguments pour l esclave
	char *argv_esclave[3];
	argv_esclave[2]=NULL;
	argv_esclave[0] = (char*) calloc(strlen(argv[2])+1, sizeof(char));
	strcpy(argv_esclave[0],argv[2]);
	 
	argv_esclave[1] = (char*) calloc(strlen(argv[3])+1, sizeof(char));
	strcpy(argv_esclave[1],argv[3]);
	//printf("strlen %lu, %lu\n", (long unsigned)strlen(argv[2]),(long unsigned) strlen(argv[3]));
	//printf("nb_esclaves %d\n", nb_esclaves);
	
	int i;
	int trouve = 0;
	int fini = 0;
	int size;
	int nb_envoi = 0;
	int nb_pas = nb_esclaves*longueur_mdp;
	int nb_changement = 0;
	char* envoi_char;
		
	int bufid, info, bytes, type, source;
	char * solution;
	pvm_catchout(stderr);
	struct timeval tv1, tv2;
	gettimeofday(&tv1, NULL);
	pvm_spawn(chemin, argv_esclave, PvmTaskDefault,"", nb_esclaves, tids);

	//calcul du pas, fin_exec (= fin execution)
	mpz_set_ui(debut_sequence, 0);
	mpz_ui_pow_ui(fin_exec, 15, longueur_mdp+1);	
	mpz_sub_ui(fin_exec, fin_exec, 15);
	mpz_cdiv_q_ui(fin_exec, fin_exec, 14);
	
	mpz_set(pas, fin_exec);
	mpz_cdiv_q_ui(pas, pas, nb_pas);
	
	if(mpz_cmp_ui(pas, 0)==0)
	  {
	    mpz_set_ui(pas,1); 
	  }

	//gmp_printf("fin_exec: %Zd\npas:%Zd\ndebut_sequence:%Zd\n",fin_exec, pas, debut_sequence);
	
	//boucle principale
	while(!trouve && fini!=nb_esclaves)
	  {
	    //Attente de reception de donnees d un esclave
	    bufid = pvm_recv( -1, -1 );
	    info = pvm_bufinfo( bufid, &bytes, &type, &source );
	    
	    if (info < 0)
	      {
		printf("Erreur de reception : %d\n", info);
		exit(1);
	      }
	    
	    //selon le tag du message, demande de donnees ou solution trouvee
	    switch(type)
	      {
	      case(0)://mot de passe trouve
		solution = calloc(bytes, sizeof(char));
		pvm_upkstr(solution);
		printf("\nLa solution est : %s\n\n", solution);
		trouve = 1;
		break;	
		
	      case(1)://esclave veut plus de donnees
		//prendre en compte la fin des donnees dans le calcul du pas
		if(nb_changement <= 2  && nb_envoi>=(3*nb_pas/4))
		  {
		    mpz_cdiv_q_ui(pas, pas, 2);
		    nb_envoi = 0;
		    nb_pas/=2;
		    nb_changement++;
		  }
		//gmp_printf("fin_exec: %Zd pas:%Zd debut_sequence:%Zd\n",fin_exec, pas, debut_sequence);
		if(mpz_cmp(debut_sequence, fin_exec)< 0){
		  mpz_sub(pas_reel, fin_exec, debut_sequence);
		  if(mpz_cmp(pas, pas_reel)<0)
		    {
		      mpz_set(pas_reel, pas);
		    }
		 		  
		  //envoi des donnes a l esclave
		  pvm_initsend(PvmDataDefault);
		  size = gmp_asprintf(&envoi_char, "%Zd", debut_sequence);
		  pvm_pkint(&size, 1, 1);
		  pvm_pkbyte(envoi_char,size+1, 1);
		  free(envoi_char);
		 
		  size = gmp_asprintf(&envoi_char, "%Zd", pas_reel);
		  pvm_pkint(&size, 1, 1);
		  pvm_pkbyte(envoi_char,size+1 , 1);
		  free(envoi_char);
		  pvm_send(source,0);
		  
		  if(mpz_cmp(pas_reel,pas)!=0)
		    {
		      mpz_set(debut_sequence,fin_exec);
		    }
		  else
		    {
		      mpz_add(debut_sequence, debut_sequence,pas);
		    }
		  nb_envoi++;
		}
		else{
		  fini++ ;
		  printf("Pas de solution pour %d esclave(s)\n", fini);
		}		
		
		break;
		
	      default:
		break;
	      }
	  }
	// suppression des esclave
	for(i=0; i<nb_esclaves;i++)
	  {
	    info = pvm_kill(tids[i]);
	    //printf("Suppression de l esclave %d: retour de pvm_kill: %d\n",i ,info);
	  }
	
	pvm_exit();
	gettimeofday(&tv2, NULL);
	printf("%d %ld\n",longueur_mdp,(tv2.tv_sec-tv1.tv_sec)*1000 + (tv2.tv_usec-tv1.tv_usec)/1000); 
	
	mpz_clear(debut_sequence);
	mpz_clear(pas_reel);
	mpz_clear(pas);
	mpz_clear(fin_exec);
	free(tids);
	free(mdp);
	free(argv_esclave[0]);
	free(argv_esclave[1]);
	
	return EXIT_SUCCESS;
}
Ejemplo n.º 25
0
int adpvm_manager::start_slave_processes_for_random_effects(const ad_comm& _mp)
{
  ad_comm& mp=(ad_comm&) _mp;
  cout << (mp.pvm_manager)->nhost;
  int i,j,check;
  mp.get_slave_assignments();
  if (allocated(id)) id.deallocate();
  id.allocate(1,nhost,1,num_per_host);
  adstring slavedir;
  int on=0;
  int use_td32=1;

  if (use_td32)
  {
    char ** pvmargs=new pchar[ad_comm::argc+5];
    int i;
    for (i=0;i<ad_comm::argc+5;i++)
    {
      pvmargs[i]=0;
    }
    pvmargs[0]=new char[strlen(ad_comm::adprogram_name)+1];
    strcpy(pvmargs[0],ad_comm::adprogram_name);

    strlwr(pvmargs[0]);
    for (i=1;i<ad_comm::argc;i++)
    {
      pvmargs[i]=new char[strlen(ad_comm::argv[i])+1];
      strcpy(pvmargs[i],ad_comm::argv[i]);
    }
    pvmargs[ad_comm::argc]=new char[strlen("-slave")+1];
    strcpy(pvmargs[ad_comm::argc],"-slave");

    pvmargs[ad_comm::argc+1]=new char[10];
    pvmargs[ad_comm::argc+3]=0;


    for (i=0;i<nhost;i++)
    {
      for (j=1;j<=num_per_host(i+1);j++)
      {
        strncpy(pvmargs[ad_comm::argc+1],
          (char*)(str(slave_assignments(i+1,j))),9);
        //check=pvm_spawn(pvmargs[0],pvmargs,
        check=pvm_spawn("td32rem",pvmargs,
          PvmTaskHost /* | PvmTaskDebug */ ,
          hostp[i].hi_name, 1, &(id(i+1,j)));
        if (!check)
          printf("Couldn't start slave process %d on %s\n",j,hostp[i].hi_name);
        else
          printf("Started slave process %d on %s\n",j,hostp[i].hi_name);
      }
    }
  }
  else
  {
    for (i=0;i<nhost;i++)
    {
      for (j=1;j<=num_per_host(i+1);j++)
      {
        check=pvm_spawn(ad_comm::adprogram_name,0,
          PvmTaskHost /* | PvmTaskDebug */ ,
          hostp[i].hi_name, 1, &(id(i+1,j)));
        if (!check)
          printf("Couldn't start slave process %d on %s\n",j,hostp[i].hi_name);
        else
          printf("Started slave process %d on %s\n",j,hostp[i].hi_name);
      }
    }
  }
  return 0;
}
Ejemplo n.º 26
0
int main(int argc, char *argv[])
{
	/*
		argv[1] - ilość narciarzy
	*/
	time_t t;
	srand((unsigned)time(&t));

	int number_of_skiers = 0;
	if (argc >= 2) {
		number_of_skiers = atoi(argv[1]);
	} else {
		number_of_skiers = rand() % 50 + 10;
	}

	printf("Liczba narciarzy: %d\n", number_of_skiers);

	int *skiers_weights;
	skiers_weights = malloc(sizeof(int) * number_of_skiers);



	int min_skier_weight = SKIERS_MAX_WEIGHT;
	int sum_skiers_weights = 0;

	int i;

	int weights_arg_index = -1;
	for (i = 0; i < argc; i++) {
		if (!strcmp(argv[i], "weights")) {
			weights_arg_index = i;
			break;
		}
	}

	for(i=0; i<number_of_skiers; i++) {
		if (weights_arg_index == -1)
			skiers_weights[i] = rand() % (SKIERS_MAX_WEIGHT - SKIERS_MIN_WEIGHT + 1) + SKIERS_MIN_WEIGHT;
		else
			skiers_weights[i] = atoi(argv[weights_arg_index + 1 + i]);
		sum_skiers_weights += skiers_weights[i];
		if (skiers_weights[i] < min_skier_weight) {
			min_skier_weight = skiers_weights[i];
		}
	}

	for(i=0; i<number_of_skiers; i++) {
		printf("Narciarz %d ma wage: %d\n", i, skiers_weights[i]);
	}
	printf("Min waga: %d\n", min_skier_weight);
	printf("Sum waga: %d\n", sum_skiers_weights);

	int min_perc_sum = 0.2 * sum_skiers_weights;
	int max_perc_sum = 0.4 * sum_skiers_weights;

	int first_lift_capacity;
	int second_lift_capacity;

	do {
		first_lift_capacity = rand() % (max_perc_sum - min_perc_sum) + min_perc_sum;
	} while (first_lift_capacity < min_skier_weight);

	do {
		second_lift_capacity = rand() % (max_perc_sum - min_perc_sum) + min_perc_sum;
	} while (second_lift_capacity < min_skier_weight);

	// read lifts capacities from console
	int lifts_arg_index = -1;
	for (i = 0; i < argc; i++) {
		if (!strcmp(argv[i], "lifts")) {
			lifts_arg_index = i;
			break;
		}
	}
	if (lifts_arg_index != -1) {
		first_lift_capacity = atoi(argv[lifts_arg_index + 1]);
		second_lift_capacity = atoi(argv[lifts_arg_index + 2]);
	}

	printf("Pierwszy wyciag: %d\n", first_lift_capacity);
	printf("Drugi wyciag: %d\n", second_lift_capacity);


	int mytid;
	int tids[number_of_skiers];		/* slave task ids */
	char slave_name[NAMESIZE];
	int nproc, j, who;

	mytid = pvm_mytid();
	pvm_catchout(stdout);

	nproc=pvm_spawn(SLAVENAME, NULL, PvmTaskDefault, "", number_of_skiers, tids);

	for( i=0 ; i<nproc ; i++ )
	{
		pvm_initsend(PvmDataDefault);
		pvm_pkint(&mytid, 1, 1);
		pvm_pkint(&number_of_skiers, 1, 1);
		for (j=0; j<nproc; j++) {
			pvm_pkint(&tids[j], 1, 1);
		}
		for (j=0; j<nproc; j++) {
			pvm_pkint(&skiers_weights[j], 1, 1);
		}
		pvm_pkint(&first_lift_capacity, 1, 1);
		pvm_pkint(&second_lift_capacity, 1, 1);
		pvm_send(tids[i], MSG_MSTR);
	}

	int current_skier_weight;

	for( i=0 ; i<nproc ; i++ )
	{
		pvm_recv( -1, MSG_SLV );
		pvm_upkint(&who, 1, 1 );
		pvm_upkstr(slave_name );
		pvm_upkint(&current_skier_weight, 1, 1);
		printf("%d: weight %d\n",who, current_skier_weight);
	}

	int msgnum = 1;
	while (1) {
		pvm_recv(-1, MSG_DIAG);
		char diag_str[200];
		pvm_upkstr(diag_str);
		printf("[%d] %s\n", msgnum, diag_str);
		msgnum++;
	}

	pvm_exit();
}
Ejemplo n.º 27
0
void BBSDirect::start() {
	char* client = 0;
	int tid, host_mytid;
	int i, n, ncpu, nncpu;
	struct pvmhostinfo* hostp;
	if (started_) { return; }
	BBSImpl::start();
	mytid_ = pvm_mytid();
	nrnmpi_myid = 0;
	if (mytid_ < 0) { perror("start"); }
	host_mytid = pvm_tidtohost(mytid_);
	tid = pvm_parent();
	if (tid == PvmSysErr) {
		perror("start");
	}else if (tid == PvmNoParent) {
		is_master_ = true;
		pvm_catchout(stdout);
		pvm_setopt(PvmRoute, PvmRouteDirect);
		pvm_config(&n, NULL, &hostp);
		nncpu = 0;
		for (i=0; i < n; ++i) {
			ncpu = hostp[i].hi_speed;
			if (ncpu%1000) {
				hoc_warning(hostp[i].hi_name,
" speed in pvm configuration file is not a multiple of 1000. Assuming 1000.");
				ncpu = 1000;
			}
			nncpu += ncpu/1000;
		}
		nrnmpi_numprocs = nncpu;
		ncids = 0;
	}else{ // a worker, impossible
		assert(false);
	}
	if (nrnmpi_numprocs > 1 && tid == PvmNoParent) {
		char ** sargv;
	// args are workingdirectory specialOrNrniv -bbs_nhost nhost args
		sargv = new char*[nrn_global_argc + 4];
		for (i=1; i < nrn_global_argc; ++i) {
			sargv[i+3] = nrn_global_argv[i];
		}
		sargv[nrn_global_argc + 3] = 0;
		sargv[0] = rel_working_dir();
//printf("sargv[0]=|%s|\n", sargv[0]);
		sargv[1] = nrn_global_argv[0];
		sargv[2] = "-bbs_nhost";
		sargv[3] = new char[10];
		sprintf(sargv[3], "%d", nrnmpi_numprocs);
		cids = new int[nrnmpi_numprocs-1];
if (nrn_global_argv[nrn_global_argc] != 0) {
	printf("argv not null terminated\n");
	exit(1);
}

		BBSDirectServer::server_->start();
		bbs_sig_set();
		bbs_handle();

		//spawn according to number of cpu's (but master has one less)
//printf("%d total number of cpus on %d machines\n", nncpu, n);
		int icid = 0;
		bool first = true;
	    while (icid < nrnmpi_numprocs - 1) {
		for (i=0; i < n; ++i) {
			ncpu = hostp[i].hi_speed;
			if (ncpu%1000) {
				ncpu = 1000;
			}
			ncpu /= 1000;
//printf("%d cpu for machine %d (%s)\n", ncpu, i, hostp[i].hi_name);
			if (first && hostp[i].hi_tid == host_mytid) {
				// spawn one fewer on master first time through
				--ncpu;
			}
			if (icid + ncpu >= nrnmpi_numprocs) {
				ncpu = nrnmpi_numprocs - icid - 1;
			}
//printf("before spawn %d processes (icid=%d) for machine %d (%s)\n", ncpu, icid, i, hostp[i].hi_name);
			if (ncpu) {
				ncids = pvm_spawn("bbswork.sh", sargv,
					PvmTaskHost, hostp[i].hi_name, ncpu, cids + icid);
				if (ncids != ncpu) {
fprintf(stderr, "Tried to spawn %d tasks, only %d succeeded on %s\n", ncpu, ncids, hostp[i].hi_name);
hoc_execerror("Could not spawn all the requested tasks for", hostp[i].hi_name);
				}
//printf("spawned %d for %s with cids starting at %d\n", ncpu, hostp[i].hi_name, icid);
				icid += ncpu;
			}
			if (icid >= nrnmpi_numprocs) {
				break;
			}
		}
		first = false;
	    }
		ncids = icid;
printf("spawned %d more %s on %d cpus on %d machines\n", ncids, nrn_global_argv[0], nncpu, n);
		delete [] sargv[3];
		delete [] sargv;
	}
}
Ejemplo n.º 28
0
int adpvm_manager::start_slave_processes(const ad_comm& _mp)
{
  ad_comm& mp=(ad_comm&) _mp;
  cout << (mp.pvm_manager)->nhost;
  int i,j,check;
  mp.get_slave_assignments();
  if (allocated(id)) id.deallocate();
  id.allocate(1,nhost,1,num_per_host);
  adstring slavedir;
  int on=0;
  int noptslave=0;

  int td32flag=option_match(ad_comm::argc,ad_comm::argv,"-td32");

  if (td32flag>0)
  {
    strcpy(*slave_argv,slave_names[1]);
  }

  if ( (on=option_match(ad_comm::argc,ad_comm::argv,"-dbg"))>-1)
     strcpy(*slave_argv,"-dbg");
  if ( (on=option_match(ad_comm::argc,ad_comm::argv,"-slavedir",noptslave))>-1)
  {
    if (noptslave !=1)
    {
      cerr << "Wrong number of options to -slavedir -- must be 1"
        " you have " << noptslave << endl;
      ad_exit(1);
    }
  }
  else
  {
    noptslave=0;
  }
  int on1,nopt1;
  if ( (on1=option_match(ad_comm::argc,ad_comm::argv,"-mcmc",nopt1))>-1)
  {
    if ( (on1=option_match(ad_comm::argc,ad_comm::argv,"-mcmc2",nopt1))>-1)
    {
      cerr << "Error -mcmc2 option not implemented for parallel processing"
           << endl;
      ad_exit(1);
    }
    if (nopt1 !=1)
    {
      cerr << "Wrong number of options to -mcmc -- must be 1"
        " you have " << noptslave << endl;
      ad_exit(1);
    }
    strcpy((*slave_argv),"-mcmc");
    strcpy((*slave_argv),ad_comm::argv[on1+1]);
  }

  if ( (on1=option_match(ad_comm::argc,ad_comm::argv,"-nohess"))>-1)
  {
    strcpy((*slave_argv),"-nohess");
  }

  if ( (on1=option_match(ad_comm::argc,ad_comm::argv,"-lprof"))>-1)
  {
    strcpy((*slave_argv),"-lprof");
  }
  int gdbflag=option_match(ad_comm::argc,ad_comm::argv,"-gdb");
  int slave_con=option_match(ad_comm::argc,ad_comm::argv,"-scon");

  int ii=0;
  for (i=0; i<nhost; i++)	/* spawn processes on */
  {				/* all physical machines */
    for (j=slave_assignments(i+1).indexmin();j<=slave_assignments(i+1).indexmax();
      j++)
    {
      strcpy((*slave_argv),"-slavename");
      strcpy((*slave_argv),ad_comm::adprogram_name);
      strcpy((*slave_argv),"-slave");
      strcpy((*slave_argv),(char*)(str(slave_assignments(i+1,j))));
      if (noptslave ==1)
      {
        strcpy((*slave_argv),"-slavedir");
        strcpy((*slave_argv),ad_comm::argv[on+1]);
      }

      if (td32flag<0)
      {
        //check=pvm_spawn(slave_names[1],*slave_argv ,
        char ** args;
        args=new pchar[10];
        args[0]=new char[20];
        args[1]=new char[20];
        strcpy(args[0],"-slave");
        strcpy(args[1],(char*)str(ii+1));
        args[2]=0;
        check=pvm_spawn(ad_comm::adprogram_name,args ,
          PvmTaskHost /* | PvmTaskDebug */ ,
          hostp[i].hi_name, 1, &(id(i+1,j)));
        ii++;
      }
      else
      {
        char ** args;
        args=new pchar[10];
        if (slave_con>0)
        {
          args[0]=new char[50];
          args[1]=new char[20];
          args[2]=new char[20];
          strncpy(args[0],ad_comm::adprogram_name,49);
          strncpy(args[1],"-slave",19);
          strncpy(args[2],(char*)str(ii+1),19);
          args[3]=0;
        }
        else
        {
          args[0]=new char[20];
          args[1]=new char[50];
          args[2]=new char[20];
          args[3]=new char[50];

          strcpy(args[0],"td32");
          strncpy(args[1],ad_comm::adprogram_name,49);
          strcpy(args[2],"-slave");
          strcpy(args[3],(char*)str(ii+1));
          args[4]=0;
        }
        //check=pvm_spawn("nrunslave",*slave_argv ,
        check=pvm_spawn("nrunslave",args ,
          PvmTaskHost /* | PvmTaskDebug */ ,
          hostp[i].hi_name, 1, &(id(i+1,j)));
        ii++;
      }

      (*slave_argv)--;
      (*slave_argv)--;
      (*slave_argv)--;
      (*slave_argv)--;
      if (noptslave ==1)
      {
        (*slave_argv)--;
        (*slave_argv)--;
      }
      if (!check)
        printf("Couldn't start process on %s\n",hostp[i].hi_name);
      else
        printf("Started process on %s\n",hostp[i].hi_name);
    }
  }
  return check;
}