예제 #1
0
render_frame()
{
	pixel Pixel_colour ;	/* pixel colour values */

	int X_counter ;		/* X axis counter */
	int Y_counter ;		/* Y axis counter */
	int Block_counter ;          /* block section counter */
	int Worker_counter ;		/* counter for the number of workers done */

	double Block_angle ;		/* angle between blocks */

	viewer Viewpoint ;		/* the viewpoint of the user */

	/* copy the users viewpoint into the working variable */
	Viewpoint.X=User.X ;
	Viewpoint.Y=User.Y ;
	Viewpoint.Z=User.Z ;
	Viewpoint.X_angle=User.X_angle ;
	Viewpoint.Y_angle=User.Y_angle ;
	Viewpoint.Z_angle=User.Z_angle ;

	/* set up the ray angles */
	Block_angle=(X_view_angle/User_view.X_size)*Pixel_buffer_width ;
	Viewpoint.Z_angle=Viewpoint.Z_angle-(X_view_angle/2)-((1/360)*2*M_PI) ;

	for (Block_counter=0;Block_counter<Number_of_workers;Block_counter++)
	{
		/* send out work to worker */
		pvm_initsend (PvmDataDefault) ;

		pvm_pkdouble(&Viewpoint.X,1,1);
		pvm_pkdouble(&Viewpoint.Y,1,1) ;
		pvm_pkdouble(&Viewpoint.Z,1,1) ;
		pvm_pkdouble(&Viewpoint.X_angle,1,1) ;
		pvm_pkdouble(&Viewpoint.Y_angle,1,1) ;
		pvm_pkdouble(&Viewpoint.Z_angle,1,1) ;

		pvm_send (Worker_tids[Block_counter],WORK) ;

		/* set the viewpoint for the next one */
		Viewpoint.Z_angle=Viewpoint.Z_angle+Block_angle ;

	}
	/* end of for loop */
	/* finished sending the data */

	/* set the number of workers finished to zero */
	Worker_counter=0 ;

	/* get the data back */
	while ( Worker_counter < Number_of_workers)
	{
		for (Block_counter=0;Block_counter<Number_of_workers;Block_counter++)
		{
			if (pvm_probe (Worker_tids[Block_counter],DATA))
				/* wait for reply */
			{
				pvm_recv (Worker_tids[Block_counter],DATA) ;
				pvm_upkbyte (Pixel_buffer,Pixel_buffer_size,1) ;

				/* increment the counter for the number of workers that have finished */
				Worker_counter=Worker_counter+1 ;

				/* copy the pixel to the image buffer */
				for (X_counter=0 ;
					X_counter<Pixel_buffer_width ;
					X_counter++ )
				{
					for (Y_counter=0;
						Y_counter<User_view.Y_size ;
						Y_counter++ )
					{
						/* copy pixel data */
						Image_buffer [(Y_counter*User_view.X_size*3)+
							(X_counter*3)+
							(Block_counter*Pixel_buffer_width*3)+
							0]
						=
							Pixel_buffer[(Y_counter*Pixel_buffer_width*3)+
							(X_counter*3)+
							0] ;

						Image_buffer[(Y_counter*User_view.X_size*3)+
							(X_counter*3)+
							(Block_counter*Pixel_buffer_width*3)+
							1]
						=
							Pixel_buffer[(Y_counter*Pixel_buffer_width*3)+
							(X_counter*3)+
							1] ;

						Image_buffer[(Y_counter*User_view.X_size*3)+
							(X_counter*3)+
							(Block_counter*Pixel_buffer_width*3)+
							2]
						=
							Pixel_buffer[(Y_counter*Pixel_buffer_width*3)+
							(X_counter*3)+
							2] ;

						/* end Y loop */
					}

					/* end X loop */
				}
			}
			/* end the if */

		}
		/* end the while loop */

		/* end drawing code */
	}

	/* copy the data to the window */
	glDrawPixels(User_view.X_size,User_view.Y_size,GL_RGB,
		GL_UNSIGNED_BYTE,Image_buffer) ;

	/* flush the graphics pipeline */
	glFlush();

}
예제 #2
0
main()
{
	GHashTable* skiers_weights = g_hash_table_new(g_str_hash, g_str_equal);
	GQueue *waiting_req_q1 = g_queue_new();
	GQueue *waiting_req_q2 = g_queue_new();

	int first_lift_free, second_lift_free;
	int mytid, mstrtid, myind, number_of_skiers, *tids, first_lift_capacity,
			second_lift_capacity, i, phase, local_clock;
	time_t t;
	char slave_name[NAMESIZE];
	char diag[200];

	struct state_info info;

	mytid = pvm_mytid();
	srand(time(NULL) + mytid);
	gethostname(slave_name, NAMESIZE);
	pvm_joingroup(GROUP);

	get_initial_values(&mstrtid, &number_of_skiers, &tids, &skiers_weights, &first_lift_capacity, &second_lift_capacity);
	info.mstrtid = mstrtid;
	first_lift_free = first_lift_capacity;
	second_lift_free = second_lift_capacity;
	int *my_weight_ptr = g_hash_table_lookup(skiers_weights, &mytid);
	int my_weight = *my_weight_ptr;

	int all_skiers_weight = 0;
	for(i=0; i<number_of_skiers; i++) {
		int *lookup = g_hash_table_lookup(skiers_weights, &tids[i]);
		all_skiers_weight += *lookup;
	}
	all_skiers_weight -= my_weight;
	sprintf(diag, "sum of all other skiers' weights = %d", all_skiers_weight);
	diag_msg(mstrtid, mytid, diag);

	i=0;
	while (tids[i] != mytid) {
		i++;
	}

	pvm_initsend(PvmDataDefault);
	pvm_pkint(&mytid, 1, 1);
	pvm_pkstr(slave_name);

	int *wat_to_send = g_hash_table_lookup(skiers_weights, &mytid);
	pvm_pkint(wat_to_send, 1, 1);
	pvm_send(mstrtid, MSG_SLV);

	// bariera
	local_clock = 0;
	pvm_barrier(GROUP, number_of_skiers);

	int time_to_wait;

	// main loop

	diag_msg(mstrtid, mytid, "entering main loop");
	while (1) {
  	int can_enter_lift = 0;
  	int chosen_lift = -1;
		int accepts_received = 0;
		int my_request_timestamp = -1;
		info.accepts_received = &accepts_received;
		info.my_request_timestamp = &my_request_timestamp;

		phase = PHASE_DOWNHILL;

		struct timeval timeout;
		random_timeout(&timeout, 3, 10);

		struct timeval start_time;
		gettimeofday(&start_time, NULL);

		struct timeval elapsed;
		elapsed.tv_sec = 0;
		elapsed.tv_usec = 0;

		sprintf(diag, "entered %s, time=%zu.%zu", stringify(phase), timeout.tv_sec, timeout.tv_usec);
		diag_msg(mstrtid, mytid, diag);
		while (1) {


			int bufid = pvm_trecv(-1, -1, &timeout);

			if (bufid) {
				// diag_msg(mstrtid, mytid, "Got message in PHASE_DOWNHILL");
				struct msg incoming_msg;
				unpack(&incoming_msg);

				int *sender_weight = g_hash_table_lookup(skiers_weights, &incoming_msg.sender_tid);

				// handle the message accordingly
        		prepare_info(&info, mytid, &local_clock, phase, &chosen_lift, &can_enter_lift,
                     &first_lift_free, &second_lift_free, incoming_msg,
										 waiting_req_q1, waiting_req_q2);
        		info.skiers_weights = skiers_weights;
        		handle_message(incoming_msg, info);
			}


			// break the loop if time elapsed is more than the timeout, else wait for another message
			struct timeval current_time;
			gettimeofday(&current_time, NULL);

			timeval_subtract(&elapsed, &current_time, &start_time);
			if (elapsed.tv_sec * 1000000 + elapsed.tv_usec >= timeout.tv_sec * 1000000 + timeout.tv_usec)
				break;
			else
				timeval_subtract(&timeout, &timeout, &elapsed);
		}

		// want to go up
		diag_msg(mstrtid, mytid, "");
		phase = PHASE_WAIT_REQUEST;

		// choose the lift (1 or 2)
		// determine if we can fit on the lift (based on our knowledge from the accepts we had sent)

		sprintf(diag, "entered PHASE_WAIT_REQUEST, weight=%d, LIFT_1=%d, LIFT_2=%d",my_weight,first_lift_free,second_lift_free);
		diag_msg(mstrtid, mytid, diag);

		if (my_weight > first_lift_free && my_weight > second_lift_free) {
			// no lift for us
			// wait for RELEASE messages until we can fit in the lift
			// meanwhile: handle all incoming messages, responding accordingly (ALWAYS respond with accepts)
			while (1) {
				sprintf(diag, "no space in lifts, weight=%d, LIFT_1=%d, LIFT_2=%d",my_weight,first_lift_free,second_lift_free);
				diag_msg(mstrtid, mytid, diag);

				int bufid = pvm_recv(-1, -1);
				struct msg incoming_msg;
				unpack(&incoming_msg);

				prepare_info(&info, mytid, &local_clock, phase, &chosen_lift, &can_enter_lift,
                     &first_lift_free, &second_lift_free, incoming_msg,
										 waiting_req_q1, waiting_req_q2);
				info.skiers_weights = skiers_weights;
        handle_message(incoming_msg, info);

				// now check if we should break the loop and go to the next phase!
				if (chosen_lift == LIFT_1 || chosen_lift == LIFT_2) {
					sprintf(diag, "weight=%d, LIFT_1=%d, LIFT_2=%d, choosing %s",
									my_weight, first_lift_free, second_lift_free, stringify(chosen_lift));
					diag_msg(mstrtid, mytid, diag);

					// broadcast a request with our chosen lift and go to (*)
					bcast_request_msg(info);
					break;
				}
			}

		}
		else { // if there is a fitting lift
			if (my_weight <= first_lift_free && my_weight > second_lift_free) { // can only go to first lift
				chosen_lift = LIFT_1;
			}
			else if (my_weight > first_lift_free && my_weight <= second_lift_free) { // can only go to second lift
				chosen_lift = LIFT_2;
			}
			else {	// can go to either lift - worst fit
				if (first_lift_free > second_lift_free)
					chosen_lift = LIFT_1;
				else if (first_lift_free < second_lift_free)
					chosen_lift = LIFT_2;
				else // equal
					chosen_lift = (rand() % 2 == 1) ? LIFT_1 : LIFT_2;
			}

			info.my_lift_number = &chosen_lift;
			info.mytid = mytid;
			info.local_clock = &local_clock;
			info.skiers_weights = skiers_weights;

			// broadcast a request with our chosen lift and go to (*)
			bcast_request_msg(info);
			// sprintf(diag,"So I am here just before broadcasting REQUEST and I choose lift %d and in info %d",chosen_lift, *info.my_lift_number);
			sprintf(diag, "weight=%d, LIFT_1=%d, LIFT_2=%d, choosing %s",
							my_weight, first_lift_free, second_lift_free, stringify(chosen_lift));
			diag_msg(mstrtid, mytid, diag);
		}

		sprintf(diag, "*** chosen_lift=%s", stringify(chosen_lift));

		// waiting for accepts (*)
    // wait for enough accepts or just as much as required to be sure that we can get in
    // meanwhile: handle all incoming messages, responding accordingly (not send back accept only to those with worse priority that can't fit together with us)
		// diag_msg(mstrtid, mytid, "entering PHASE_WAIT_ACCEPTS");
		phase = PHASE_WAIT_ACCEPTS;
		int pending = all_skiers_weight;
		info.pending_accepts_sum = &pending;

		sprintf(diag, "entered PHASE_WAIT_ACCEPTS, lift=%s", stringify(chosen_lift));
		diag_msg(mstrtid, mytid, diag);

		while (1) {
			int bufid = pvm_recv(-1, -1);
			struct msg incoming_msg;
			unpack(&incoming_msg);

			prepare_info(&info, mytid, &local_clock, phase, &chosen_lift, &can_enter_lift,
									&first_lift_free, &second_lift_free, incoming_msg,
									waiting_req_q1, waiting_req_q2);
      handle_message(incoming_msg, info);

			// check if there are enough amount of acceptes - can break the loop and go to the critical section
			if (can_enter_lift) {
				break;
			}
		}

		// random waiting up to the hill - critical section
		phase = PHASE_CRITICAL;

		random_timeout(&timeout, 3, 10);

		gettimeofday(&start_time, NULL);

		elapsed.tv_sec = 0;
		elapsed.tv_usec = 0;

		sprintf(diag, "entered PHASE_CRITICAL, lift=%s, time=%zu.%zu",
						stringify(chosen_lift), timeout.tv_sec, timeout.tv_usec);
		diag_msg(mstrtid, mytid, diag);

		while (1) {
			int bufid = pvm_trecv(-1, -1, &timeout);
			if (bufid) {
				// unpack the received message
				struct msg incoming_msg;
				// int msgtag = -1, sender_tid = -1, lift_number = -1, timestamp = -1;
				unpack(&incoming_msg);

				// handle the message accordingly
				prepare_info(&info, mytid, &local_clock, phase, &chosen_lift, &can_enter_lift,
                     &first_lift_free, &second_lift_free, incoming_msg,
										 waiting_req_q1, waiting_req_q2);
        handle_message(incoming_msg, info);
			}

			// break the loop if time elapsed is more than the timeout, else wait for another message
			struct timeval current_time;
			gettimeofday(&current_time, NULL);

			timeval_subtract(&elapsed, &current_time, &start_time);
			if (elapsed.tv_sec * 1000000 + elapsed.tv_usec >= timeout.tv_sec * 1000000 + timeout.tv_usec)
				break;
			else
				timeval_subtract(&timeout, &timeout, &elapsed);
		}

		// release - broadcast the RELEASE message to all others
		info.mytid = mytid;
		info.local_clock = &local_clock;
		info.my_lift_number = &chosen_lift;
		bcast_release_msg(info);

		// send all the requests stored in the queue (mcast automatically clears it)
		mcast_accept_msg(info);
	}

	pvm_exit();
}
예제 #3
0
int 
main(void)
{
  struct p7trace_s *tr;         /* traceback of an alignment               */
  int      master_tid;		/* PVM TID of our master */
  char    *hmmfile;	        /* file to read HMM(s) from                */
  HMMFILE *hmmfp;               /* opened hmmfile for reading              */
  struct plan7_s *hmm;
  char    *seq;
  char    *dsq;
  int      len;
  int      nhmm;		/* number of HMM to work on                */
  float    sc;
  int      my_idx = -1;		/* my index, 0..nslaves-1 */
  float    globT;		/* T parameter: keep only hits > globT bits */
  double   globE;		/* E parameter: keep hits < globE E-value   */
  double   pvalue;		/* Z*pvalue = Evalue                        */
  int      Z;			/* nseq to base E value calculation on      */
  int      send_trace;		/* TRUE if score is significant             */
  int      do_xnu;		/* TRUE to do XNU filter on seq             */
  int      do_forward;		/* TRUE to use Forward() scores not Viterbi */
  int      do_null2;		/* TRUE to correct scores w/ ad hoc null2   */
  int      alphatype;		/* alphabet type, hmmAMINO or hmmNUCLEIC    */
  int      code;		/* return code after initialization         */

  
  /* Register leave_pvm() cleanup function so any exit() call
   * first calls pvm_exit().
   */
  if (atexit(leave_pvm) != 0) { pvm_exit(); Die("slave couldn't register leave_pvm()"); }

  /*****************************************************************
   * initialization.
   * Master broadcasts to us: 
   *     1) len of HMM file name        (int)
   *     2) name of HMM file            (string)
   *     3) length of sequence string   (int) 
   *     4) sequence                    (string)
   *     5) globT threshold
   *     6) globE threshold
   *     7) Z 
   *     8) do_xnu flag
   *     9) do_forward flag
   *    10) do_null2 flag
   *    11) alphabet type
   * We receive the broadcast and open the files.    
   ******************************************************************/

  master_tid = pvm_parent();	/* who's our master? */

  pvm_recv(master_tid, HMMPVM_INIT);
  pvm_upkint(&len, 1, 1);
  hmmfile = MallocOrDie(sizeof(char *) * (len+1));
  pvm_upkstr(hmmfile);
  pvm_upkint(&len, 1, 1);
  seq = MallocOrDie(sizeof(char *) * (len+1));
  pvm_upkstr(seq);
  pvm_upkfloat(&globT, 1, 1);
  pvm_upkdouble(&globE, 1, 1);
  pvm_upkint(&Z, 1, 1);
  pvm_upkint(&do_xnu, 1, 1);
  pvm_upkint(&do_forward, 1, 1);
  pvm_upkint(&do_null2, 1, 1);
  pvm_upkint(&alphatype, 1, 1);

  SetAlphabet(alphatype);
				/* Open HMM file (maybe in HMMERDB) */
  code = HMMPVM_OK;
  if ((hmmfp = HMMFileOpen(hmmfile, "HMMERDB")) == NULL)
    code = HMMPVM_NO_HMMFILE;
  else if (hmmfp->gsi == NULL)
    code = HMMPVM_NO_INDEX;
  
  /* report our status.
   */
  pvm_initsend(PvmDataDefault);
  pvm_pkint(&code, 1, 1);	
  pvm_send(master_tid, HMMPVM_RESULTS);

  dsq = DigitizeSequence(seq, len);
  if (do_xnu) XNU(dsq, len);

  /*****************************************************************
   * Main loop.
   * Receive an integer 0..nhmm-1 for which HMM to search against.
   * If we receive a -1, we shut down. 
   *****************************************************************/ 
  
  for (;;) 
    {
      pvm_recv(master_tid, HMMPVM_WORK);
      pvm_upkint(&nhmm, 1, 1);
      if (my_idx < 0) my_idx = nhmm; /* first time thru, remember what index we are. */

      if (nhmm == -1) break;	/* shutdown signal */

      /* move to our assigned HMM in the HMM file, and read it
       */
      HMMFilePositionByIndex(hmmfp, nhmm);
      if (! HMMFileRead(hmmfp, &hmm)) Die("unexpected end of HMM file"); 
      if (hmm == NULL)                Die("unexpected failure to parse HMM file"); 
      P7Logoddsify(hmm, TRUE);
      
      /* Score sequence, do alignment (Viterbi), recover trace
       */
      if (P7ViterbiSize(len, hmm->M) <= RAMLIMIT)
	{
	  SQD_DPRINTF1(("P7Viterbi(): Estimated size %d Mb\n", P7ViterbiSize(len, hmm->M)));
	  sc = P7Viterbi(dsq, len, hmm, &tr);
	}
      else
	{
	  SQD_DPRINTF1(("P7SmallViterbi() called; %d Mb > %d\n", P7ViterbiSize(len, hmm->M), RAMLIMIT));
	  sc = P7SmallViterbi(dsq, len, hmm, &tr);
	}

      if (do_forward) sc  = P7Forward(dsq, len, hmm, NULL);
      if (do_null2)   sc -= TraceScoreCorrection(hmm, tr, dsq);
	
      pvalue = PValue(hmm, sc);
      send_trace = (sc > globT && pvalue * (float) Z < globE) ? 1 : 0;

      /* return output
       */
      pvm_initsend(PvmDataDefault);
      pvm_pkint(&my_idx, 1, 1);	/* tell master who we are */
      pvm_pkstr(hmm->name);	/* double check that we did the right thing */
      pvm_pkfloat(&sc, 1, 1);
      pvm_pkdouble(&pvalue, 1, 1);
      pvm_pkint(&send_trace, 1, 1); /* flag for whether a trace structure is coming */
      if (send_trace) PVMPackTrace(tr);
      pvm_send(master_tid, HMMPVM_RESULTS);

      /* cleanup
       */
      FreePlan7(hmm);
      P7FreeTrace(tr);
    }

  /*********************************************** 
   * Cleanup, return.
   ***********************************************/

  HMMFileClose(hmmfp);
  free(seq);
  free(dsq);
  free(hmmfile);
  return 0;
}
예제 #4
0
int SendMessage(int in_reciever, message* in_message, msg_type in_type) {
	pvm_initsend(PvmDataDefault);
	pvm_pkbyte((char*)in_message, sizeof(message), 1);
	return pvm_send(in_reciever, in_type);
}
예제 #5
0
파일: parallel.c 프로젝트: girving/kalah
/* send off a completed job */
void send_done(jobinfo *j) {
  add_stolen(0,j->jid);
  pvm_initsend(0);
  pkjobinfo_done(j);
  pvm_send(j->tid,TAG_DONE);
  }
예제 #6
0
int main(int argc, char** argv)
{
   int pid = pvm_mytid();

   if (argc != 2 && argc != 3)
      stop("Usage: tm_driver <control_file> [TM_tid]\n");

   int tm_tid = 0;
   char * control_file = strdup(argv[1]);

   if (argc == 3)
      sscanf(argv[2], "t%x", &tm_tid);

   int info = 0;

   // Get the machine configuration
   int nhost = 0;
   int narch = 0;
   struct pvmhostinfo *hostp = 0;
   info = pvm_config(&nhost, &narch, &hostp);

   // Parse the control file
   int to_delete_size = 0;  // # of machsto delete
   char ** to_delete = 0;   // names of machs to delete
   int to_add_size = 0;     // # of machsto add
   char ** to_add = 0;      // names of machs to add

   int delete_proc_num = 0; // # of procs to delete
   int * tid_delete = 0;    // the tids of procs to delete

   // # of various procs to start
   int lp_num = 0;
   int cg_num = 0;
   int vg_num = 0;
   int cp_num = 0;
   int vp_num = 0;
   // the mach names where the procs shoud be started
   char ** lp_mach = 0;
   char ** cg_mach = 0;
   char ** vg_mach = 0;
   char ** cp_mach = 0;
   char ** vp_mach = 0;

   // Do the parsing. First count
   ifstream ctl(control_file);
   if (!ctl)
      stop("Cannot open parameter file... Aborting.\n");
   // Get the lines of the parameter file one-by-one and if a line contains a
   // (keyword, value) pair then interpret it.
   const int MAX_PARAM_LINE_LENGTH = 1024;
   char line[MAX_PARAM_LINE_LENGTH+1], *end_of_line, *keyword, *value, *ctmp;
   char ch;
   while (ctl) {
      ctl.get(line, MAX_PARAM_LINE_LENGTH);
      if (ctl) {
	 ctl.get(ch);
	 if (ch != '\n') {
	    printf("Too long (>= %i chars) line in the parameter file.\n",
		   MAX_PARAM_LINE_LENGTH);
	    stop("This is absurd. Aborting.\n");
	 }
      }
      end_of_line = line + strlen(line);
      //-------------------------- First separate the keyword and value ------
      keyword = find_if(line, end_of_line, isgraph);
      if (keyword == end_of_line) // empty line
	 continue;
      ctmp = find_if(keyword, end_of_line, isspace);
      if (ctmp == end_of_line) // line is just one word. must be a comment
	 continue;
      *ctmp = 0; // terminate the keyword with a 0 character
      ++ctmp;

      value = find_if(ctmp, end_of_line, isgraph);
      if (value == end_of_line) // line is just one word. must be a comment
	 continue;
      
      ctmp = find_if(value, end_of_line, isspace);
      *ctmp = 0; // terminate the value with a 0 character. this is good even
		 // if ctmp == end_ofline

      if (str_eq(keyword, "BCP_delete_machine")) {
	 ++to_delete_size;
      } else if (str_eq(keyword, "BCP_add_machine")) {
	 ++to_add_size;
      } else if (str_eq(keyword, "BCP_delete_proc")) {
	 ++delete_proc_num;
      } else if (str_eq(keyword, "BCP_lp_process")) {
	 ++lp_num;
      } else if (str_eq(keyword, "BCP_cg_process")) {
	 ++cg_num;
      } else if (str_eq(keyword, "BCP_vg_process")) {
	 ++vg_num;
      } else if (str_eq(keyword, "BCP_cp_process")) {
	 ++cp_num;
      } else if (str_eq(keyword, "BCP_vp_process")) {
	 ++vp_num;
      }
   }
   ctl.close();

   if (to_delete_size > 0) {
      to_delete = new char*[to_delete_size];
      to_delete_size = 0;
   }
   if (to_add_size > 0) {
      to_add = new char*[to_add_size];
      to_add_size = 0;
   }
   if (delete_proc_num > 0) {
      tid_delete = new int[delete_proc_num];
      delete_proc_num = 0;
   }
   if (lp_num) {
      lp_mach = new char*[lp_num];
      lp_num = 0;
   }
   if (cg_num) {
      cg_mach = new char*[cg_num];
      cg_num = 0;
   }
   if (vg_num) {
      vg_mach = new char*[vg_num];
      vg_num = 0;
   }
   if (cp_num) {
      cp_mach = new char*[cp_num];
      cp_num = 0;
   }
   if (vp_num) {
      vp_mach = new char*[vp_num];
      vp_num = 0;
   }

   ctl.open(control_file);
   while (ctl) {
      ctl.get(line, MAX_PARAM_LINE_LENGTH);
      if (ctl) {
	 ctl.get(ch);
	 if (ch != '\n') {
	    printf("Too long (>= %i chars) line in the parameter file.\n",
		   MAX_PARAM_LINE_LENGTH);
	    stop("This is absurd. Aborting.\n");
	 }
      }
      end_of_line = line + strlen(line);
      //-------------------------- First separate the keyword and value ------
      keyword = find_if(line, end_of_line, isgraph);
      if (keyword == end_of_line) // empty line
	 continue;
      ctmp = find_if(keyword, end_of_line, isspace);
      if (ctmp == end_of_line) // line is just one word. must be a comment
	 continue;
      *ctmp = 0; // terminate the keyword with a 0 character
      ++ctmp;

      value = find_if(ctmp, end_of_line, isgraph);
      if (value == end_of_line) // line is just one word. must be a comment
	 continue;
      
      ctmp = find_if(value, end_of_line, isspace);
      *ctmp = 0; // terminate the value with a 0 character. this is good even
		 // if ctmp == end_ofline

      if (str_eq(keyword, "BCP_delete_machine")) {
	 to_delete[to_delete_size++] = strdup(value);
      } else if (str_eq(keyword, "BCP_add_machine")) {
	 to_add[to_add_size++] = strdup(value);
      } else if (str_eq(keyword, "BCP_delete_proc")) {
	 sscanf(value, "t%x", &tid_delete[delete_proc_num++]);
      } else if (str_eq(keyword, "BCP_lp_process")) {
	 lp_mach[lp_num++] = strdup(value);
      } else if (str_eq(keyword, "BCP_cg_process")) {
	 cg_mach[cg_num++] = strdup(value);
      } else if (str_eq(keyword, "BCP_vg_process")) {
	 vg_mach[vg_num++] = strdup(value);
      } else if (str_eq(keyword, "BCP_cp_process")) {
	 cp_mach[cp_num++] = strdup(value);
      } else if (str_eq(keyword, "BCP_vp_process")) {
	 vp_mach[vp_num++] = strdup(value);
      }
   }
   ctl.close();

   // Check that machine deletions and additions are correct

   char ** last = 0;

   // Are there duplicates on the to be deleted list ?
   if (to_delete_size > 0) {
      sort(to_delete, to_delete + to_delete_size, str_lt);
      last = unique(to_delete, to_delete + to_delete_size, str_eq);
      if (to_delete_size != last - to_delete)
	 stop("A machine to be deleted is listed twice... Aborting.\n");
   }

   // Are there duplicates on the to be added list?
   if (to_add_size > 0) {
      sort(to_add, to_add + to_add_size, str_lt);
      last = unique(to_add, to_add + to_add_size, str_eq);
      if (to_add_size != last - to_add)
	 stop("A machine to be added is listed twice... Aborting.\n");
   }

   int i;
   char ** mach_list = new char*[nhost + to_add_size];
   for (i = 0; i < nhost; ++i)
      mach_list[i] = strdup(hostp[i].hi_name);
   sort(mach_list, mach_list + nhost, str_lt);

   char ** current_list = new char*[nhost + to_add_size];

   // Is there a nonexisting machine to be deleted?
   if (to_delete_size > 0) {
      last = set_difference(to_delete, to_delete + to_delete_size,
			    mach_list, mach_list + nhost,
			    current_list, str_lt);
      if (last != current_list)
	 stop("A nonexisting machine is to be deleted... Aborting.\n");
      last = set_difference(mach_list, mach_list + nhost,
			    to_delete, to_delete + to_delete_size,
			    current_list, str_lt);
      ::swap(mach_list, current_list);
   }

   // Is there an already existing machine to be added?
   if (to_add_size > 0) {
      last = set_intersection(to_add, to_add + to_add_size,
			      mach_list, mach_list + nhost,
			      current_list, str_lt);
      if (last != current_list)
	 stop("A machine to be added is already there... Aborting.\n");
      last = merge(to_add, to_add + to_add_size,
		   mach_list, mach_list + nhost,
		   current_list, str_lt);
      ::swap(mach_list, current_list);
   }

   const int mach_num = nhost - to_delete_size + to_add_size;

   // Check that the machines the new processes are supposed to be started on
   // really exist.

   if (lp_num > 0) {
      sort(lp_mach, lp_mach + lp_num, str_lt);
      if (set_difference(lp_mach, lp_mach + lp_num,
			 mach_list, mach_list + mach_num,
			 current_list, str_lt) != current_list)
	 stop("An lp machine is not in the final machine list... Aborting.\n");
   }
   if (cg_num > 0) {
      sort(cg_mach, cg_mach + cg_num, str_lt);
      if (set_difference(cg_mach, cg_mach + cg_num,
			 mach_list, mach_list + mach_num,
			 current_list, str_lt) != current_list)
	 stop("An cg machine is not in the final machine list... Aborting.\n");
   }
   if (vg_num > 0) {
      sort(vg_mach, vg_mach + vg_num, str_lt);
      if (set_difference(vg_mach, vg_mach + vg_num,
			 mach_list, mach_list + mach_num,
			 current_list, str_lt) != current_list)
	 stop("An vg machine is not in the final machine list... Aborting.\n");
   }
   if (cp_num > 0) {
      sort(cp_mach, cp_mach + cp_num, str_lt);
      if (set_difference(cp_mach, cp_mach + cp_num,
			 mach_list, mach_list + mach_num,
			 current_list, str_lt) != current_list)
	 stop("An cp machine is not in the final machine list... Aborting.\n");
   }
   if (vp_num > 0) {
      sort(vp_mach, vp_mach + vp_num, str_lt);
      if (set_difference(vp_mach, vp_mach + vp_num,
			 mach_list, mach_list + mach_num,
			 current_list, str_lt) != current_list)
	 stop("An vp machine is not in the final machine list... Aborting.\n");
   }

   // Find the tree manager
   find_tree_manager(pid, tm_tid);

   // Check that the TM is not on one of the machines to be deleted.
   if (to_delete_size > 0) {
      const int dtid = pvm_tidtohost(tm_tid);
      for (i = 0; i < nhost; ++i) {
	 if (hostp[i].hi_tid == dtid)
	    for (int j = 0; j < to_delete_size; ++j) {
	       if (str_eq(hostp[i].hi_name, to_delete[j]))
		  stop("Can't delete the machine the TM is on. Aborting.\n");
	    }
      }
   }

   // Check that the TM is not one of the processes to be deleted
   if (delete_proc_num > 0) {
      if (find(tid_delete, tid_delete + delete_proc_num, tm_tid) !=
	  tid_delete + delete_proc_num)
	 stop("Can't delete the TM... Aborting.\n");
   }

   // Modify the machine configuration
   if (to_delete_size > 0 || to_add_size > 0) {
      int * infos = new int[max(to_delete_size, to_add_size)];
      if (to_delete_size > 0)
	 if (pvm_delhosts(to_delete, to_delete_size, infos) < 0) {
	    printf("Failed to delete all specified machines...\n");
	    stop("Please check the situation manually... Aborting.\n");
	 }
      if (to_add_size > 0)
	 if (pvm_addhosts(to_add, to_add_size, infos) < 0) {
	    printf("Failed to add all specified machines...\n");
	    stop("Please check the situation manually... Aborting.\n");
	 }
   }

   // Kill the processes to be killed
   for (i = 0; i < delete_proc_num; ++i)
      pvm_kill(tid_delete[i]);

   // Put together a message to be sent to the TM that contains the machine
   // names on which the new processes should be spawned
   int len = (lp_num + cg_num + vg_num + cp_num + vp_num) * sizeof(int);
   if (len > 0) {
      len += 5 * sizeof(int);
      for (i = 0; i < lp_num; ++i) len += strlen(lp_mach[i]);
      for (i = 0; i < cg_num; ++i) len += strlen(cg_mach[i]);
      for (i = 0; i < vg_num; ++i) len += strlen(vg_mach[i]);
      for (i = 0; i < cp_num; ++i) len += strlen(cp_mach[i]);
      for (i = 0; i < vp_num; ++i) len += strlen(vp_mach[i]);

      char * buf = new char[len];

      memcpy(buf, &lp_num, sizeof(int));
      buf += sizeof(int);
      for (i = 0; i < lp_num; ++i) {
	 const int l = strlen(lp_mach[i]);
	 memcpy(buf, &l, sizeof(int));
	 buf += sizeof(int);
	 memcpy(buf, lp_mach[i], l);
	 buf += l;
      }

      memcpy(buf, &cg_num, sizeof(int));
      buf += sizeof(int);
      for (i = 0; i < cg_num; ++i) {
	 const int l = strlen(cg_mach[i]);
	 memcpy(buf, &l, sizeof(int));
	 buf += sizeof(int);
	 memcpy(buf, cg_mach[i], l);
	 buf += l;
      }

      memcpy(buf, &vg_num, sizeof(int));
      buf += sizeof(int);
      for (i = 0; i < vg_num; ++i) {
	 const int l = strlen(vg_mach[i]);
	 memcpy(buf, &l, sizeof(int));
	 buf += sizeof(int);
	 memcpy(buf, vg_mach[i], l);
	 buf += l;
      }

      memcpy(buf, &cp_num, sizeof(int));
      buf += sizeof(int);
      for (i = 0; i < cp_num; ++i) {
	 const int l = strlen(cp_mach[i]);
	 memcpy(buf, &l, sizeof(int));
	 buf += sizeof(int);
	 memcpy(buf, cp_mach[i], l);
	 buf += l;
      }

      memcpy(buf, &vp_num, sizeof(int));
      buf += sizeof(int);
      for (i = 0; i < vp_num; ++i) {
	 const int l = strlen(vp_mach[i]);
	 memcpy(buf, &l, sizeof(int));
	 buf += sizeof(int);
	 memcpy(buf, vp_mach[i], l);
	 buf += l;
      }

      buf -= len;

      pvm_initsend(PvmDataRaw);
      pvm_pkbyte(buf, len, 1);
      pvm_send(tm_tid, BCP_CONFIG_CHANGE);

      int bufid = pvm_recv(tm_tid, -1);
      int bytes = 0, msgtag = 0;
      pvm_bufinfo(bufid, &bytes, &msgtag, &tm_tid);
      if (msgtag == BCP_CONFIG_ERROR)
	 stop("TM had difficulties. Please check the situation manually.\n");
   }

   pvm_exit();
   return 0;
}
예제 #7
0
파일: mandel-basic.c 프로젝트: fip/FIP3A
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);
}
예제 #8
0
void WorkersLoop(int startupflags)
{
  double theta;
  long daytime, newtinc;
  Entity et;
  Vector sunpos;
  VarDesc *v;
  int i, j, k;
  char varname[80];
  while (1)  {
    switch (GetCommand())  {
    case DO_TIME_STEP :
      if (plausible)  {
	daytime = ((int)(timeofday*3600.)+actime) % 86400;
	ActualiseValuesInTime(actime);	/* Actualise Border values */
	for (et = maxentity; et--; )
	  CalculateLayerAverage(g[et], pstat, avg+et*nz);
	SetAvgMountains();
	CalcMeanHydrostaticPressure();
	InterpolateToFaces();			/* Interpolate wind speeds from center to faces */
	InterpolateToCenter(-1., pressuretype == NONHYDROSTATIC);
	if (tstart == actime)  Continuity();
	CheckTimeStep(&tinc, &chemtinc, 0.8);
	if (pressuretype == NONHYDROSTATIC)
	  ApplyBuoyancy(tinc);			/* Calculate Buoyancy */
	if (pressuretype != NOPRESSURE)  {		/* Calc wind acceleration */
	  switch (pressuretype)  {			/* Calculate Pressure field */
	  case HYDROSTATIC    : CalcHydrostaticPressure(); break;
	  case NONHYDROSTATIC : SolveForPressure(tinc); break;
	  }
	  ApplyPressure(tinc);
	}
	Continuity();				/* Mass conservation */
	InterpolateToCenter(1., pressuretype == NONHYDROSTATIC);
	if (coriolistype != NOCORIOLIS)  ApplyCoriolis(tinc);
	if (filtertype != NO_FILTER)  {
	  SetBoundary(WWIND+1);   /* Set Boundary for Wind only */
	  switch (filtertype)  {
	  case PEPPER_FILTER :
	    for (i = nz; i--; )
	      for (et = HUMIDITY; et--; )
		ApplyFilter(g[et]+i*layer, pstat+i*layer, spatialfilter);
	    break;
	  case SHAPIRO_FILTER :
	    for (i = nz; i--; )
	      for (et = HUMIDITY; et--; )
		ShapiroFilter(g[et]+i*layer, pstat+i*layer, 3, spatialfilter);
	    break;
	  case DIFFUSION_FILTER :
	    for (i = nz; i--; )
	      for (et = HUMIDITY; et--; )
		ShapiroFilter(g[et]+i*layer, pstat+i*layer, 1, spatialfilter);
	    break;
	  }
	}
	SetBoundary(WWIND+1);
	CheckTimeStep(&newtinc, &chemtinc, 1.);
	if (newtinc < tinc)  {
	  tinc = newtinc;
	}
	chemtinc = (chemtime <= actime ? chemtinc : 0);
	if (advection || windadvection)
	  switch (advectiontype)  {
	  case MPDATA_A : Advect(tinc, chemtinc); break;
	  case PPM_A    : PPM_Transport(tinc, chemtinc, smiord); break;
	  }
	if (dampinglayer)  DampTop();
	if (groundinterface || shortwaveradiation)  {
	  GroundInterface(timeofday + (double)actime / 3600., dayofyear, tinc, &sunpos);
	  sunelevation = (sunpos.z > 0. ? 57.29578 * asin(sunpos.z) : 0.);
	}
	if (cloudwater)  CloudPhysics();
	if (turbtype == TTTT)  {
	  if (groundinterface)
	    CalcGroundTurbulence(tinc);
	  CalcTransilientTurbulence(tinc);
	}
	else if (turbtype == KEPS_T)  {
	  CalcKEpsilon(tinc);
	  if (groundinterface)
	    CalcGroundTurbulence(tinc);
	  CalcKTurb(tinc, chemtinc);
	}
	Emit(tinc);
	Deposit(tinc);
	if (!(radiationtype && shortwaveradiation) &&
	    // When using the two-stream module, ChemicalTimeStep
	    // mus be called from within ShortWaveRadiation!
	    nsubs && actime % tchem == 0)  ChemicalTimeStep(tchem, &sunpos);
	SetBoundary(chemtinc ? maxentity : SUBS);
    
	// Call ModuleManager
	McInterface::modmanager.DoCalc(actime+tinc);

	actime += tinc; chemtime += chemtinc;
	if (dumpnow || (dumptime && (actime % dumptime == 0)))  {
	  MakeAFullDump();
	  dumpnow = 0;
	}
      }  /* if (plausible) */
      SendStatus(plausible);
      break;
    case SENDGRIDVAL :
      pvm_upkint((int *)&et, 1, 1);
      pvm_upkint(&i, 1, 1);
      pvm_upkint(&j, 1, 1);
      pvm_upkint(&k, 1, 1);
      pvm_initsend(PvmDataRaw);
      pvm_pkdouble(g[et]+i*row+j+k*layer, 1, 1);
      pvm_send(myparent, VALUES);
      break;
    case SENDMESHVAL :
      pvm_upkstr(varname);
      v = GetNamedVar(varname);
      pvm_upkint(&i, 1, 1);
      pvm_upkint(&j, 1, 1);
      pvm_upkint(&k, 1, 1);
      pvm_initsend(PvmDataRaw);
      if (v->storetype == PROC_VAL)  {
	theta = v->v.proc(k, i, j, v);
	pvm_pkdouble(&theta, 1, 1);
      }
      else
	pvm_pkdouble(GetNamedVar(varname)->v.d+i*row+j+k*layer, 1, 1);
      pvm_send(myparent, VALUES);
      break;
    case SENDGRID :
      pvm_upkint((int *)&et, 1, 1);
      SendMeshToMaster(g[et], 0, ALL_DIM);
      break;
    case SENDMESH :
      pvm_upkstr(varname);
      v = GetNamedVar(varname);
      if (v->storetype == PROC_VAL)  {
	for (k = nz; k--; )
	  for (i = nx+1; i--; )
	    for (j = ny+1; j--; )
	      flux[0][i*row+j+k*layer] = v->v.proc(k, i, j, v);
	SendMeshToMaster(flux[0], 0, v->dims);
	memset(flux[0], 0, mesh * sizeof(double));
      }
      else
	SendMeshToMaster(v->v.d, 0, v->dims);
      break;
    case SENDGROUND :
      SendGroundToMaster();
      break;
    case EXIT :
      pvm_exit();
      exit (0);
    }
  }
}
예제 #9
0
파일: craquage.c 프로젝트: lysbleu/pvm-bss
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;
}
예제 #10
0
파일: master.c 프로젝트: skoneka/prir
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;
}
예제 #11
0
int main(int argc, char **argv)
	 
{
  unsigned long	i = 1;
  char		Err[BUFSIZ];
#ifdef PVM
  unsigned int	j = 0L;
#endif

  
  /* There is no signal handling under parix. */
  if(((int)signal(SIGINT, (void (*)(int)) myInterrupt) == -1) ||
	 ((int)signal(SIGFPE, (void (*)(int)) Arithmetic) == -1))
	panic(A_FATAL, "child-main", "signal call went wrong :%s : %d",
		  __FILE__, __LINE__);
  
  strcpy(hlp, argv[0]);
  program_name = hlp;
  
  initDef(&eps);				/* initialize structure */
  ipOptPrc(&eps, argc, argv);	/* process options. */
  
#ifdef PVM
  eps.tid  = pvm_mytid();        /* tid of process. */
  strcpy(eps.Group, eps.Suffix); /* Create Group name. */
  if((eps.inst = pvm_joingroup(eps.Group)) < 0)
	panic(A_FATAL, "child-main", 
		  "pvm grouping for group %s failed : %s : %d\n",
		  eps.Group, __FILE__, __LINE__);

  printf("Slave with tid %d and inst %d started\n", eps.tid, eps.inst);

  /* To get more diversity, each Population gets other external parameters.*/
  
  if(eps.SigDim > 0)
	eps.SigStart += (0.1 * (double) eps.inst);

  /*
  if(eps.SigDim > 0) {
	if(eps.SigDim == 1)
	  eps.TauOne *= (0.1 * (double) eps.inst);
	else
	  eps.TauLcl *= (0.1 * (double) eps.inst);
  }
  
  if(eps.PDim > 0) {
	if(eps.PDim == 1) {
	  eps.GamOne *= (double) eps.inst;
	  eps.PStart *= (double) eps.inst;
	}
	else
	  eps.GamLcl *= (double) eps.inst;
  }
  
#ifdef DEBUG
  fprintf(stderr, "%d:Tau = %g, Gamma = %g\n",
          eps.inst, eps.TauLcl, eps.GamOne);
#endif 
  */

  sprintf(&hlp[strlen(hlp)], ".%d", eps.tid);
  if(pvm_barrier(eps.Group, eps.Tasks+1) < 0)
	panic(A_WARN, "child-main", "pvm barrier error : %s : %d\n",
		  __FILE__, __LINE__);
  printf("\n%s as instance %d activ.\n", program_name, eps.inst);
  
#endif /* PVM */
  
  if(ipOptChk(&eps, Err)) {	  /* check parameter consistency */
	fprintf(stderr,"%s",Err); /* print warning message */
	panic(A_FATAL, "ipOptPrc", "Parameter inconsistency :\n%s\n%s : %d", 
		  Err, __FILE__, __LINE__);
  }
  
#ifndef PVM
  printf("\n%s activ.\n", program_name);
#endif	
  
#ifdef PVM
  if(NULL == (MigrationBuffer = (individual_tPtr *)
			  calloc(eps.Neighbours, sizeof(individual_tPtr))))
	panic(E_FATAL, "main-child", "not enough memory : %s : %d",
		  __FILE__, __LINE__);
  
  for(j = 0; j < eps.Neighbours; j++)
	MigrationBuffer[j]= inNewIndividual(eps.XDim, eps.DDim, eps.SigDim,
										eps.AlpDim, eps.PDim);
#endif

  initSuffix(&eps);			/* initialize suffix,
							   here string from ES.in*/
  parsFormatString(&eps);	/* pars format string */
  
  pop = poNewPopulation(&eps);
  
  for (i = 1; i <= eps.TotExp; i++) {  /* experiment loop */
	
	ExpNbr = i;
	
	initPop(&eps, pop, i);

#ifdef PVM
	/* Initialization of MigrationBuffer. */
	for(j = 0; j < eps.Neighbours; j++) {
	  if(j < pop->mu)
		inCopyIndividual(poGetIndividual(j+1, pop),
						 MigrationBuffer[j]);
	  else
		inCopyIndividual(poGetIndividual(pop->mu, pop),
						 MigrationBuffer[j]);
	}
#endif
	
	dataParLog(&eps);		/* dump parameters */
	fioTimeOut(&eps);		/* get start time */
	
	PopulationEVAL(&eps, pop, "parents");
	dataCol(&eps, pop, i);
	if (eps.GfxFlg)
	  gnInitGnuPipe(&eps);
	
#ifdef PVM
	send_Best(&eps, pop);
#endif
	
	while (!termExp(&eps)) { /* ES main loop */
	  
	  eps.GenCnt++;
	  PopulationCREATE(&eps, pop);
	  /* recombination and mutation including the
		 concept of letal mutations. */
	  PopulationEVAL(&eps, pop, "offspring");
	  PopulationSELECT(&eps, pop);
	  dataCol(&eps, pop, i);
	  if(eps.GfxFlg && (eps.GenCnt % eps.GfxIvl == 0))
		gnPlotGnuPipe(&eps);     /* plot data */

#ifdef PVM
	  send_Best(&eps, pop);
	  if(eps.GenCnt % eps.IsolationTime == 0) {
		send_Neighbours(&eps, pop);
		if(eps.Communication == COMMUNICATION_SYNCHRON)
		  recv_sync(&eps, MigrationBuffer);
	  }
	  if(eps.Communication == COMMUNICATION_ASYNCHRON)
		recv_async(&eps, MigrationBuffer);
	  for(j = 0; j < eps.Neighbours && j < pop->mu; j++)
		inCopyIndividual(MigrationBuffer[j],
					     poGetIndividual(j+1, pop));
#endif

	}  /* end ES main loop */
	
	dataBst(&eps, pop, i); /* dump best ind. */
	fioTimeOut(&eps);	   /* get end time */
	
  } /* end experiment loop */
  
  if(eps.GfxFlg)
	gnQuitGnuPipe(&eps);	/* stop plotting */
  
  reportExperiments(&eps);
  
  pop = poDeletePopulation(pop);
  
#ifdef PVM
  if(pvm_initsend(PvmDataRaw) < 0)
	panic(A_FATAL,"child-main", "initsend for group %d failed : %s : %d",
		  eps.inst, __FILE__, __LINE__);
  
  if((ptid = pvm_parent()) == PvmNoParent)
	panic(A_FATAL,"child-main", "pvm_parent for group %d failed : %s : %d",
		  eps.inst, __FILE__, __LINE__);
  
  if(pvm_pkint(&(eps.tid), 1, 1) < 0)
	panic(A_FATAL,"child-main", "packing of tid failed : %s : %d",
		  __FILE__, __LINE__);
  
  if(pvm_send(ptid, MSGTAG_END) < 0)
	panic(A_WARN, "child-main", 
		  "sending end message to master failed : %s : %d",
		  __FILE__, __LINE__);
  pvm_barrier(eps.Group, eps.Tasks+1);
  pvm_lvgroup(eps.Group);
	
  for(j = 0; j < eps.Neighbours; j++)
	inDeleteIndividual(MigrationBuffer[j]);
  free(MigrationBuffer);
#endif
	
  utGlobalTermination(&eps);
	
  printf("\n%s 1.0 terminated.\n", program_name);

#ifdef PVM
  pvm_exit();
#endif

  exit(0);
}
예제 #12
0
void myInterrupt(int dummy)
	 
{
#ifdef PVM
  unsigned int	j = 0;
#endif
  
#ifndef PVM
  char		    choice = 'c';
  unsigned long	trials = 0;
  bool		      flag = TRUE;
  
  
  printf("\nActual optimization situation :\n");
  printf("\n-------------------------------\n\n");
  
  printf("\nGenCnt\t= %ld", eps.GenCnt);
  printf("\nTrlCnt\t= %ld\n", eps.TrlCnt);
  
  if((eps.XDim != 0) || (eps.DDim != 0)) {
	printf("AllBest\t= %g\n",eps.AllBst);
	printf("CurBst\t= %g\n",eps.CurBst);
	printf("CurAvg\t= %g\n",eps.CurAvg);
	printf("CurWst\t= %g\n\n",eps.CurWst);
  }
  if(eps.SigDim != 0) {
	printf("SigMin\t= %g\n",eps.SigMin);
	printf("SigAvg\t= %g\n",eps.SigAvg);
	printf("SigMax\t= %g\n\n",eps.SigMax);
  }
  if(eps.AlpDim != 0) {
	printf("CorMin\t= %g\n",eps.CorMin);
	printf("CorAvg\t= %g\n",eps.CorAvg);
	printf("CorMax\t= %g\n\n",eps.CorMax);
  }
  if(eps.PDim != 0) {
	printf("PMin\t= %g\n",eps.PMin);
	printf("PAvg\t= %g\n",eps.PAvg);
	printf("PMax\t= %g\n\n",eps.PMax);
  }
  
  printf("\nTotTrl\t= %ld",eps.TotTrl);
  while(flag) {
	printf("\nMore trials ? (0 / new number of trials)\n");
	scanf("%ld", &trials);
	if(trials != 0) {
	  if(trials <= eps.TrlCnt)
		printf("\nNumber of trials below TrlCnt\n");
	  else {
		eps.TotTrl = trials;
		printf("\nTotTrl set to %ld\n",eps.TotTrl);
		flag = FALSE;
	  }
	}
	else
	  flag = FALSE;
  }
  
  while(TRUE) {
	printf("\nTermination/Continuation ? (t/c)\n");
	scanf("%c", &choice);
	if((choice == 't') || (choice == 'c'))
	  break;
  }
  
  if(choice == 't') {
#endif

	fioTimeOut(&eps);
	dataBst(&eps, pop, ExpNbr);
	if(eps.GfxFlg)
	  gnQuitGnuPipe(&eps);
	if(eps.ObjFlg)
	  fclose(eps.FpObj);
	if(eps.DisFlg)
	  fclose(eps.FpDis);
	if(eps.SigFlg)
	  fclose(eps.FpSig);
	if(eps.AlpFlg)
	  fclose(eps.FpAlp);
	if(eps.RatFlg)
	  fclose(eps.FpRat);
	fclose(eps.FpOut);
	fclose(eps.FpLog);
	poDeletePopulation(pop);

#ifdef PVM
	if(pvm_initsend(PvmDataRaw) < 0)
	  panic(A_FATAL,"child-main", "initsend for group %d failed : %s : %d",
			eps.inst, __FILE__, __LINE__);
	
	if((ptid = pvm_parent()) == PvmNoParent)
	  panic(A_FATAL,"child-main", "pvm_parent for group %d failed : %s : %d",
			eps.inst, __FILE__, __LINE__);
	
	if(pvm_pkint(&(eps.tid), 1, 1) < 0)
	  panic(A_FATAL,"child-main", "packing of tid failed : %s : %d", 
			__FILE__, __LINE__);

	if(pvm_send(ptid, MSGTAG_END) < 0)
	  panic(A_WARN, "child-main", 
			"sending end message to master failed : %s : %d",
			__FILE__, __LINE__);
	pvm_barrier(eps.Group, eps.Tasks+1);
	pvm_lvgroup(eps.Group);
	
	for(j = 0; j < eps.Neighbours; j++)
	  inDeleteIndividual(MigrationBuffer[j]);
	free(MigrationBuffer);
#endif

	utGlobalTermination(&eps);
	
	printf("\n%s 1.0 terminated.\n", program_name);

#ifdef PVM
	pvm_exit();
#endif		

	exit(0);
	
#ifndef PVM
  }
  
  printf("\n%s 1.0 continued.\n", program_name);
  return;
#endif

}
예제 #13
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;
}
예제 #14
0
파일: PVM.c 프로젝트: 1587/ltp
void SendTime(ArgStruct * p, double *t)
{
	pvm_initsend(PVMDATA);
	pvm_pkdouble(t, 1, 1);
	pvm_send(p->prot.othertid, 1);
}
예제 #15
0
// To evolve the genetic algorithm, we loop through all of our populations and
// tell each process to evolve its population for a certain number of 
// generations.  Then allow the migrator to do its thing.  Each process is
// supposed to keep track of the statistics for its population, so we reap 
// those as well.
void
PVMDemeGA::step() {
  if(_mid == 0) return;

#ifdef DEBUG
  cerr << "sending step command to slaves...\n";
#endif

  for(int j=0; j<_ntid; j++) {
    int nsteps = 10;
    _status = pvm_initsend(PvmDataDefault);
    _status = pvm_pkint(&nsteps, 1, 1);
    _status = pvm_send(_tid[j], MSG_STEP);
  }

#ifdef DEBUG
  cerr << "waiting for slaves to step...\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);
      switch(msgtag) {
      case MSG_STEP_COMPLETE:
	flag--;

#ifdef DEBUG
	cerr << "  tid " << tid << " has finished step\n";
#endif
	break;

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

  migrate();

// Now update the statistics and individuals in our local populations.  We copy
// all of the distributed individuals into our own populations then do the
// statistics updates.  Since we copy, we don't force any new evaluations.  If
// you don't need to keep the master up-to-date, then comment out this section
// and just let the slaves run on their own.

  collect();

  for(unsigned int jj=0; jj<npop; jj++)
    pstats[jj].update(*deme[jj]);

  stats.numsel = stats.numcro = stats.nummut = stats.numrep = stats.numeval=0;
  for(unsigned int kk=0; kk<npop; kk++) {
    pop->individual(kk).copy(deme[kk]->best());
    stats.numsel += pstats[kk].numsel;
    stats.numcro += pstats[kk].numcro;
    stats.nummut += pstats[kk].nummut;
    stats.numrep += pstats[kk].numrep;
    stats.numeval += pstats[kk].numeval;
  }

  pop->touch();
  stats.update(*pop);
  for(unsigned int ll=0; ll<npop; ll++)
    stats.numpeval += pstats[ll].numpeval;
}
예제 #16
0
파일: PVM.c 프로젝트: 1587/ltp
void SendRepeat(ArgStruct * p, int rpt)
{
	pvm_initsend(PVMDATA);
	pvm_pkint(&rpt, 1, 1);
	pvm_send(p->prot.othertid, 1);
}
예제 #17
0
/* Function: main_loop_pvm()
 * Date:     SRE, Wed Aug 19 13:59:54 1998 [St. Louis]
 *
 * Purpose:  Given an HMM and parameters for synthesizing random
 *           sequences; return a histogram of scores.
 *           (PVM version)  
 *
 * Args:     hmm     - an HMM to calibrate.
 *           seed    - random number seed
 *           nsample - number of seqs to synthesize
 *           lumpsize- # of seqs per slave exchange; controls granularity
 *           lenmean - mean length of random sequence
 *           lensd   - std dev of random seq length
 *           fixedlen- if nonzero, override lenmean, always this len
 *           hist       - RETURN: the score histogram 
 *           ret_max    - RETURN: highest score seen in simulation
 *           extrawatch - RETURN: total CPU time spend in slaves.
 *           ret_nslaves- RETURN: number of PVM slaves run.
 *
 * Returns:  (void)
 *           hist is alloc'ed here, and must be free'd by caller.
 */
static void
main_loop_pvm(struct plan7_s *hmm, int seed, int nsample, int lumpsize,
	      float lenmean, float lensd, int fixedlen,
	      struct histogram_s **ret_hist, float *ret_max, 
	      Stopwatch_t *extrawatch, int *ret_nslaves)
{
  struct histogram_s *hist;
  int                 master_tid;
  int                *slave_tid;
  int                 nslaves;
  int                 nsent;	/* # of seqs we've asked for so far       */
  int                 ndone;	/* # of seqs we've got results for so far */
  int		      packet;	/* # of seqs to have a slave do           */
  float               max;
  int                 slaveidx;	/* id of a slave */
  float              *sc;        /* scores returned by a slave */
  Stopwatch_t         slavewatch;
  int                 i;
  
  StopwatchZero(extrawatch);
  hist = AllocHistogram(-200, 200, 100);
  max  = -FLT_MAX;

  /* Initialize PVM
   */
  if ((master_tid = pvm_mytid()) < 0)
    Die("pvmd not responding -- do you have PVM running?");
#if DEBUGLEVEL >= 1
  pvm_catchout(stderr);		/* catch output for debugging */
#endif
  PVMSpawnSlaves("hmmcalibrate-pvm", &slave_tid, &nslaves);

  /* Initialize the slaves
   */
  pvm_initsend(PvmDataDefault);
  pvm_pkfloat(&lenmean,       1, 1);
  pvm_pkfloat(&lensd,         1, 1);
  pvm_pkint(  &fixedlen,      1, 1);
  pvm_pkint(  &Alphabet_type, 1, 1);
  pvm_pkint(  &seed,          1, 1);
  if (! PVMPackHMM(hmm)) Die("Failed to pack the HMM");
  pvm_mcast(slave_tid, nslaves, HMMPVM_INIT);
  SQD_DPRINTF1(("Initialized %d slaves\n", nslaves));

  /* Confirm slaves' OK status.
   */
  PVMConfirmSlaves(slave_tid, nslaves);
  SQD_DPRINTF1(("Slaves confirm that they're ok...\n"));
 
  /* Load the slaves
   */
  nsent = ndone = 0;
  for (slaveidx = 0; slaveidx < nslaves; slaveidx++)
    {
      packet    = (nsample - nsent > lumpsize ? lumpsize : nsample - nsent);

      pvm_initsend(PvmDataDefault);
      pvm_pkint(&packet,    1, 1);
      pvm_pkint(&slaveidx,  1, 1);
      pvm_send(slave_tid[slaveidx], HMMPVM_WORK);
      nsent += packet;
    }
  SQD_DPRINTF1(("Loaded %d slaves\n", nslaves));

  /* Receive/send loop
   */
  sc = MallocOrDie(sizeof(float) * lumpsize);
  while (nsent < nsample)
    {
				/* integrity check of slaves */
      PVMCheckSlaves(slave_tid, nslaves);

				/* receive results */
      SQD_DPRINTF2(("Waiting for results...\n"));
      pvm_recv(-1, HMMPVM_RESULTS);
      pvm_upkint(&slaveidx,   1, 1);
      pvm_upkint(&packet,     1, 1);
      pvm_upkfloat(sc,   packet, 1);
      SQD_DPRINTF2(("Got results.\n"));
      ndone += packet;

				/* store results */
      for (i = 0; i < packet; i++) {
	AddToHistogram(hist, sc[i]);
	if (sc[i] > max) max = sc[i];
      }
				/* send new work */
      packet    = (nsample - nsent > lumpsize ? lumpsize : nsample - nsent);

      pvm_initsend(PvmDataDefault);
      pvm_pkint(&packet,    1, 1);
      pvm_pkint(&slaveidx,  1, 1);
      pvm_send(slave_tid[slaveidx], HMMPVM_WORK);
      SQD_DPRINTF2(("Told slave %d to do %d more seqs.\n", slaveidx, packet));
      nsent += packet;
    }
      
  /* Wait for the last output to come in.
   */
  while (ndone < nsample)
    {
				/* integrity check of slaves */
      PVMCheckSlaves(slave_tid, nslaves);

				/* receive results */
      SQD_DPRINTF1(("Waiting for final results...\n"));
      pvm_recv(-1, HMMPVM_RESULTS);
      pvm_upkint(&slaveidx, 1, 1);
      pvm_upkint(&packet,   1, 1);
      pvm_upkfloat(sc, packet, 1);
      SQD_DPRINTF2(("Got some final results.\n"));
      ndone += packet;
				/* store results */
      for (i = 0; i < packet; i++) {
	AddToHistogram(hist, sc[i]);
	if (sc[i] > max) max = sc[i];
      }
    }

  /* Shut down the slaves: send -1,-1,-1.
   */
  pvm_initsend(PvmDataDefault);
  packet = -1;
  pvm_pkint(&packet, 1, 1);
  pvm_pkint(&packet, 1, 1);
  pvm_pkint(&packet, 1, 1);
  pvm_mcast(slave_tid, nslaves, HMMPVM_WORK);

  /* Collect stopwatch results; quit the VM; return.
   */
  for (i = 0; i < nslaves; i++)
    {
      pvm_recv(-1, HMMPVM_RESULTS);
      pvm_upkint(&slaveidx, 1, 1);
      StopwatchPVMUnpack(&slavewatch);

      SQD_DPRINTF1(("Slave %d finished; says it used %.2f cpu, %.2f sys\n",
		    slaveidx, slavewatch.user, slavewatch.sys));

      StopwatchInclude(extrawatch, &slavewatch);
    }

  free(slave_tid);
  free(sc);
  pvm_exit();
  *ret_hist    = hist;
  *ret_max     = max;
  *ret_nslaves = nslaves;
  return;
}
예제 #18
0
파일: parallel.c 프로젝트: girving/kalah
/* send a cancel message to a process */
inline void send_cancel(int tid, int jid) {
  pvm_initsend(0);
  pvm_pkint(jid,1,1);
  pvm_send(tid,TAG_CANCEL);
  }
예제 #19
0
int update_kolejka(){
	int tid_rycerza;
	int czasid_rycerza;
	int typ_wiadomosci;

		//pthread_mutex_lock(&sem_recv);

		//SendMessagetoMaster("PRZED MESSAGE");
		//Odbieramy
		if(pvm_trecv(-1, MSG_CZASID, &timeout) > 0){
			//pvm_recv(-1,MSG_CZASID);
			pvm_upkint(&typ_wiadomosci,1,1);	
			pvm_upkint(&tid_rycerza,1,1);
			pvm_upkint(&czasid_rycerza,1,1);

			//pthread_mutex_unlock(&sem_recv);

			//SendMessagetoMaster("START MESSAGE");


			if(typ_wiadomosci == CONFIRM){
				//SendMessagetoMaster("Przyszla wiadomosc od rycerza do rycerza: CONFIRM");
					ile_odpowiedzialo ++ ;
					if(ile_odpowiedzialo == RYCERZE-1){
						wszyscy_odpowiedzieli = 1 ;
						ile_odpowiedzialo = 0 ;	
						//SendMessagetoMaster("WSZYSCY: CONFIRM");		
					}
				//Update
				update_rycerz(tid_rycerza,czasid_rycerza);

			
			}
			else if (typ_wiadomosci == REQUEST){
				//SendMessagetoMaster("Przyszla wiadomosc od rycerza do rycerza: REQUEST");		
		
				//Update
				update_rycerz(tid_rycerza,czasid_rycerza);

				//SendMessagetoMaster("Po update REQUEST");		
				//Wysylamy

				pvm_initsend(PvmDataDefault);
				int typ = CONFIRM ;
				pvm_pkint(&typ,1,1);
				pvm_pkint(&tid_rycerza,1,1);
				int moj_czasid = getCzasId(mytid);
				pvm_pkint(&moj_czasid,1,1);
				pvm_send(tid_rycerza, MSG_CZASID);

				//SendMessagetoMaster("PO WYSLANIU CONFIRM");

			}
			else{
				SendMessagetoMasterTyp("WTF ? Co to za typ_wiadomosci ?",typ_wiadomosci);	
			}

			//SendMessagetoMaster("END MESSAGE");
		
			if(wszyscy_odpowiedzieli == 1){
				return 1 ;	
			}else{
				return 0 ;
			}
		}
		else{
			return 0 ;		
		}
		
}
예제 #20
0
파일: parallel.c 프로젝트: girving/kalah
/* message handling routine */
void p_handle(int b) {
  int i,k,len,tid,tag;
  jobinfo *j;
  jobinfo tj; 
  pvm_bufinfo(b,&len,&tag,&tid);

  switch (tag) {
    case TAG_HELLO:
      if (master) {
        wtid = realloc(wtid,sizeof(int) * ++nw);
        wtid[nw-1] = tid;
        for (i=1;i<nw;i++) {
          pvm_initsend(0);
          k = i << BASE_SHIFT;
          pvm_pkint(&k,1,1);
          pvm_pkint(&nw,1,1);
          pvm_pkint(wtid,nw,1);
          pvm_send(wtid[i],TAG_WORKERS);
          }
        }
      break;

    case TAG_WORKERS: 
      pvm_upkint(&nextjid,1,1);      
      nextjid <<= BASE_SHIFT;
      pvm_upkint(&nw,1,1);
      free(wtid);
      wtid = malloc(sizeof(int) * nw);
      pvm_upkint(wtid,nw,1);
      break;

    case TAG_KILL:
      die("Received TAG_KILL.  Too lazy to do anything useful.\n");

    case TAG_REQUEST:
      if (j = freejob()) {
        pvm_initsend(0);
        pkjobinfo_active(j);
        pvm_send(tid,TAG_JOB);
        add_stolen(tid,j->jid);
        free(j);
        }
      else if (!victim(tid)) {
        pvm_initsend(0);
        pvm_send(tid,TAG_NO_JOB);
        }
      break; 

    case TAG_DONE:
      upkjobinfo_done(&tj);
      if (cj && cj->jid == tj.pjid)
        slow_absorb(cj,&tj.s);
      else if (!tj.jid && master) {
        j = malloc(sizeof(jobinfo)); 
        *j = tj;
        add_jobarray(j);
        }
      else if ((i = find_jobarray(tj.pjid)) >= 0) { 
        slow_absorb(ja[i],&tj.s);
        if (ja[i]->status == JOB_DONE && !(!ja[i]->jid && master)) {
          send_done(ja[i]);
          free(ja[i]); 
          del_jobarray(i);
          }
        }
      else if (tj.tid = find_stolen(tj.pjid))  // if 0, job was cancelled
        send_done(&tj);
      break; 
    
    case TAG_CANCEL:
      pvm_upkint(&k,1,1); 
      if (cj && cj->jid == k) {
        cj->status = JOB_CANCELLED;
        if (p_head > 0) 
          cancel_children(cj);
        p_head = 1000;
        add_stolen(0,cj->jid);
        }
      else if ((i = find_jobarray(k)) >= 0) { 
        cancel_children(ja[i]);
        add_stolen(0,ja[i]->jid); 
        free(ja[i]);
        del_jobarray(i);
        }
      else if (tid = find_stolen(k)) 
        send_cancel(tid,k); 
      break;

    case TAG_STAT:
    default:
      die("Warning: ignoring invalid message\n");
    }
  }
예제 #21
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;

}
예제 #22
0
파일: Manager.c 프로젝트: barroca/Anthill
/** This sends filter data to all filters we have in the layout
 * \param layout the void layout
 */
static void sendFiltersData(Layout *layout) {
    FilterSpec *pFilter;
    int i, j, k, x;
    printf("Manager.c: sending filter data now\n");

#ifdef VOID_INST
    //build instrumentation directory(a string like 1-1-1, which is the number of instances of all filters)
    //this is the same for all filters, so we build here and send inside the loop
    char instDir[MAX_IDIR_LENGTH];
    sprintf(instDir, "%s/", INST_DIR);
    for (i=0; i < layout->numFilters-1; i++) {
        if (strlen(instDir) >= (MAX_IDIR_LENGTH - 3)) {
            //dont want to overflow this array
            fprintf(stderr, "%s %d: warning, instrumentation directory name too big, truncating to %s\n", __FILE__, __LINE__, instDir);
            break;
        }
        sprintf(instDir, "%s%d-", instDir, layout->filters[i]->filterPlacement.numInstances);
    }
    sprintf(instDir, "%s%d", instDir, layout->filters[layout->numFilters-1]->filterPlacement.numInstances);
#endif

    for(i = 0; i < layout->numFilters; i++) {
        pFilter = layout->filters[i];

#ifdef ATTACH
        // if this is a filter of the type attach it wait for another process attach him
        // so we dont need send information about layout now, because the process tha
        // attach this filter go to do it.
        if(pFilter->attach) continue;
#endif
        //for each instance of the filter, we send its data
        for (j=0; j < pFilter->filterPlacement.numInstances; j++) {
            int l1, l2, l3, l4, l5, l6, l7, res, pTid;

            //we send only one message with all information inside
            pvm_initsend(PvmDataRaw);
            //Teste
            //current working directory
            l1 = strlen(layout->cwd);
            pvm_pkint(&l1, 1, 1);
            pvm_pkbyte(layout->cwd, l1, 1);

            //send filterID
            pvm_pkint(&i, 1, 1);
            // rank
            pvm_pkint(&j, 1, 1);
            // total number of instances of this filter
            pvm_pkint(&pFilter->filterPlacement.numInstances, 1, 1);
            //send all tids of this filter
            pvm_pkint(pFilter->filterPlacement.tids, pFilter->filterPlacement.numInstances, 1);

#ifdef ATTACH
            pTid = pvm_mytid();
            // if you are using attach your parent in this moment
            // can be other process and not the guy that create you
            // so the parent must send his tid
            pvm_pkint(&pTid, 1, 1);

            // this said if this filter have been attached to this pipeline
            // its usefull because this filter cant finish with a msg of
            // the type EOF from this manager
            pvm_pkint(&pFilter->attached ,1, 1);
#endif
#ifdef BMI_FT
            // indicates the fault status: NO_FAULT, FAULT_OTHER_FILTER_INST,
            // or filter instance rank
            pvm_pkint(&pFilter->faultStatus, 1, 1);

            // if this filter is the last filter in the pipeline
            pvm_pkint(&pFilter->lastFilter, 1, 1);
#endif
            // filtername
            l2 = strlen(pFilter->name);
            pvm_pkint(&l2, 1, 1);
            pvm_pkbyte(pFilter->name, l2, 1);

            //machine memory
            HostsStruct *h = layout->hostsStruct;
            int hostIndex = hostsGetIndexByName(h, pFilter->filterPlacement.hosts[j]);
            int memory = hostsGetMemory(h, hostIndex);
            pvm_pkint(&memory, 1, 1);

            //how many brothers do I have in this machine?(used for memory management)
            int z, numLocalInstances = 0; // me and my brothers
            for (z=0; z < pFilter->filterPlacement.numInstances; z++) {
                if (strncmp(pFilter->filterPlacement.hosts[z], pFilter->filterPlacement.hosts[j], MAX_HNAME_LENGTH) == 0) {
                    numLocalInstances++;
                }
            }
            pvm_pkint(&numLocalInstances, 1, 1);

#ifdef VOID_INST
            int lInst;

            //send instrumentation directory
            lInst = strlen(instDir);
            pvm_pkint(&lInst, 1, 1);
            pvm_pkbyte(instDir, lInst, 1);
#endif
            // shared lib name
            l3 = strlen(pFilter->libname);
            pvm_pkint(&l3, 1, 1);
            pvm_pkbyte(pFilter->libname, l3, 1);

            //port data
            //numOutputs
            pvm_pkint(&pFilter->numOutputs, 1, 1);
            //numInputs
            pvm_pkint(&pFilter->numInputs, 1, 1);

            // OutputPorts
            // for each OutputPort
            // Alterado por FELIPE
            // Because now every filter output can have
            // many destinations, we are implementing a
            // loop to send the information of each destination filter
            for(k = 0; k < pFilter->numOutputs; k++) {
                //port data
                //ITAMAR numToSend = numbers of 'to' one from has
                pvm_pkint(&(pFilter->outputs[k]->numToSend), 1, 1);

                l4 = strlen(pFilter->outputs[k]->fromPortName);
                pvm_pkint(&l4, 1, 1);
                pvm_pkbyte(pFilter->outputs[k]->fromPortName, l4, 1);  //portname

                //stream tag
                pvm_pkint(&pFilter->outputs[k]->tag, 1, 1);

                for( x = 0; x < pFilter->outputs[k]->numToSend; x++ )
                {
                    //number of tids & tids
                    pvm_pkint(&pFilter->outputs[k]->toFilter[x]->filterPlacement.numInstances, 1, 1);

                    pvm_pkint(pFilter->outputs[k]->toFilter[x]->filterPlacement.tids,
                              pFilter->outputs[k]->toFilter[x]->filterPlacement.numInstances, 1); //tids

                    //write policy name
                    l5 = strlen(pFilter->outputs[k]->writePolicyName[x]);
                    pvm_pkint(&l5, 1, 1);
                    pvm_pkbyte(pFilter->outputs[k]->writePolicyName[x], l5, 1);

                    writePolicy_t wp = getWritePolicyByName(pFilter->outputs[k]->writePolicyName[x]);

                    // send labeled stream libname if policy is LS
                    if ( (wp == LABELED_STREAM) || (wp == MULTICAST_LABELED_STREAM) ) {
                        l6 = strlen(pFilter->outputs[k]->lsLibName[x]);
                        pvm_pkint(&l6, 1, 1);
                        pvm_pkbyte(pFilter->outputs[k]->lsLibName[x], l6, 1);
                    }
                    else {
                        //if not LS, we need know who will be the first instance to receive msgs
                        //else we can create hotspots
                        //we use the rank % number of receiving instances
                        res = j % pFilter->outputs[k]->toFilter[x]->filterPlacement.numInstances;
                        pvm_pkint(&res, 1, 1);
                    }
                }
            }

            // InputPorts
            // foreach InputPort
            for(k = 0; k < pFilter->numInputs; k++) {

                int ind_toPort;

                // Search for the index corresponding to current filter in the
                // destinations of current stream
                for(x = 0; x < pFilter->inputs[k]->numToSend; x++) {

                    if( strcmp(pFilter->name, pFilter->inputs[k]->toFilter[x]->name) == 0 ) { // Found it!

                        ind_toPort = x;
                        break;
                    }

                }

                //portName
                l7 = strlen(pFilter->inputs[k]->toPortName[ind_toPort]);
                pvm_pkint(&l7, 1, 1);
                pvm_pkbyte(pFilter->inputs[k]->toPortName[ind_toPort], l7, 1);

                //number of tids we listen to
                pvm_pkint(&pFilter->inputs[k]->fromFilter->filterPlacement.numInstances, 1, 1); // number of instances
                pvm_pkint(pFilter->inputs[k]->fromFilter->filterPlacement.tids,
                          pFilter->inputs[k]->fromFilter->filterPlacement.numInstances, 1); //the tids of the instances
                pvm_pkint(&pFilter->inputs[k]->tag, 1, 1); //the stream tag

                writePolicy_t wp = getWritePolicyByName(pFilter->inputs[k]->writePolicyName[x]);
                int aux = 0;
                // send labeled stream libname if policy is LS
                if ( (wp == LABELED_STREAM) || (wp == MULTICAST_LABELED_STREAM) ) {
                    // yes it has a label
                    aux = 1;
                    pvm_pkint(&aux, 1, 1);
                    l6 = strlen(pFilter->inputs[k]->lsLibName[x]);
                    pvm_pkint(&l6, 1, 1);
                    pvm_pkbyte(pFilter->inputs[k]->lsLibName[x], l6, 1);
                } else {
                    pvm_pkint(&aux, 1, 1);
                }


            }
            pvm_send(pFilter->filterPlacement.tids[j], 0);
        }
    }
}
예제 #23
0
int 
main(void)
{
  int      master_tid;		/* PVM TID of our master */
  int      slaveidx;		/* my slave index (0..nslaves-1) */
  struct plan7_s *hmm;		/* HMM to calibrate, sent from master */
  struct histogram_s *hist;     /* score histogram */
  int      hmmidx;		/* index of this HMM */
  char    *seq;			/* synthetic random sequence */
  char    *dsq;			/* digitized seq */
  int      len;			/* length of seq */
  float    sc;			/* score of seq aligned to HMM */
  float    max;			/* maximum score seen in sample */
  int      seed;		/* random number seed */
  int      nsample;		/* number of seqs to sample */
  int      fixedlen;		/* if nonzero, fixed length of seq */
  float    lenmean;		/* Gaussian mean length of seq */
  float    lensd;		/* Gaussian length std. dev. for seq */
  int      fitok;		/* TRUE if EVD fit was OK */
  float    randomseq[MAXABET];	/* iid frequencies of residues */
  float    p1;
  int      alphatype;		/* alphabet type, hmmAMINO or hmmNUCLEIC    */
  int      idx;
  int      code;

  /* Register leave_pvm() cleanup function so any exit() call
   * first calls pvm_exit().
   */
  if (atexit(leave_pvm) != 0) { pvm_exit(); Die("slave couldn't register leave_pvm()"); }

  /*****************************************************************
   * initialization.
   * Master broadcasts the problem to us: parameters of the
   * HMM calibration.  
   ******************************************************************/

  master_tid = pvm_parent();	/* who's our master? */

  pvm_recv(master_tid, HMMPVM_INIT);
  pvm_upkint(&nsample,  1, 1);
  pvm_upkint(&fixedlen, 1, 1);
  pvm_upkfloat(&lenmean,  1, 1);
  pvm_upkfloat(&lensd,    1, 1);

  /* tell the master we're OK and ready to go (or not)
   */
  code = HMMPVM_OK;
  pvm_initsend(PvmDataDefault);
  pvm_pkint(&code, 1, 1);	
  pvm_send(master_tid, HMMPVM_RESULTS);

  /*****************************************************************
   * Main loop.
   * Receive a random number seed, then an HMM to search against.
   * If we receive a -1 seed, we shut down. 
   *****************************************************************/ 
  
  slaveidx = -1;
  for (;;) 
    {
      pvm_recv(master_tid, HMMPVM_WORK);
      pvm_upkint(&seed, 1, 1);
      if (seed == -1) break;	/* shutdown signal */
      pvm_upkint(&hmmidx, 1, 1);
      pvm_upkint(&alphatype,1, 1);
      SetAlphabet(alphatype);
      hmm = PVMUnpackHMM();
      if (hmm == NULL) Die("oh no, the HMM never arrived");

      if (slaveidx == -1) slaveidx = hmmidx; 
      P7DefaultNullModel(randomseq, &p1);

      sre_srandom(seed);
      P7Logoddsify(hmm, TRUE);
      hist = AllocHistogram(-200, 200, 100);
      max  = -FLT_MAX;

      for (idx = 0; idx < nsample; idx++)
	{
  				/* choose length of random sequence */
	  if (fixedlen) len = fixedlen;
	  else do len = (int) Gaussrandom(lenmean, lensd); while (len < 1);
				/* generate it */
	  seq = RandomSequence(Alphabet, randomseq, Alphabet_size, len);
	  dsq = DigitizeSequence(seq, len);

	  if (P7ViterbiSize(len, hmm->M) <= RAMLIMIT)
	    sc = P7Viterbi(dsq, len, hmm, NULL);
	  else
	    sc = P7SmallViterbi(dsq, len, hmm, NULL);

	  AddToHistogram(hist, sc);
	  if (sc > max) max = sc;
	  
	  free(seq);
	  free(dsq);
	}

      /* Fit an EVD to the observed histogram.
       * The TRUE left-censors and fits only the right slope of the histogram.
       * The 9999. is an arbitrary high number that means we won't trim outliers
       * on the right.
       */
      fitok = ExtremeValueFitHistogram(hist, TRUE, 9999.);

      /* Return output to master.
       * Currently we don't send the histogram back, but we could.
       */
      pvm_initsend(PvmDataDefault);
      pvm_pkint(&slaveidx, 1, 1);
      pvm_pkint(&hmmidx, 1, 1);	
      PVMPackString(hmm->name);
      pvm_pkint(&fitok,  1, 1);
      pvm_pkfloat(&(hist->param[EVD_MU]), 1, 1);
      pvm_pkfloat(&(hist->param[EVD_LAMBDA]), 1, 1);
      pvm_pkfloat(&max, 1, 1);
      pvm_send(master_tid, HMMPVM_RESULTS);

      /* cleanup
       */
      FreeHistogram(hist);
      FreePlan7(hmm);
    }

  /*********************************************** 
   * Cleanup, return.
   ***********************************************/

  return 0;			/* pvm_exit() is called by atexit() registration. */
}
예제 #24
0
int
Establish(ArgStruct *p)
{
    /* Task information for the entire parallel machine (if trans) */
    int                     tasks_status;
    struct pvmtaskinfo      *taskp;
    int                     ntasks;

        /* Received buffer (if receiver)  */
    int buffer_id;

    /*
    If we are the transmitting side, go find the other one and send
    it a message containing our tid. If we are the receiving side,
    just wait for a message.
    */
    if (p->tr) {
#ifdef DEBUG
	printf("this is the transmitter\n");
#endif
	tasks_status = pvm_tasks( 0, &ntasks, &taskp );
	if (ntasks != 2) {
	    printf("Error, too many processes in parallel machine \n");
	    printf("Start a clean machine.  n=%d\n", ntasks);
	    exit(-1);
	}

	/* Since there are two tasks, one is ours the other is the receiver */
	p->prot.othertid = -1;
	if (taskp[0].ti_tid == p->prot.mytid) {
	    p->prot.othertid = taskp[1].ti_tid;
	}
	if (taskp[1].ti_tid == p->prot.mytid) {
	    p->prot.othertid = taskp[0].ti_tid;
	}
	if (p->prot.othertid == -1) {
	    printf("Error, cannot find other (receiving) task \n");
	    printf("Id's:  %d %d  \n",taskp[0].ti_tid,taskp[1].ti_tid);
	}

	/* Send the receiver a message.  Tell pvm to keep the channel open */

#ifdef DEBUG
	printf("The receiver tid is %d \n",p->prot.othertid);
#endif
	pvm_setopt( PvmRoute, PvmRouteDirect );
	pvm_initsend( PVMDATA );
	pvm_pkint( &p->prot.mytid, 1, 1 );
	pvm_send( p->prot.othertid, 1 );
    } else {
#ifdef DEBUG
	printf("This is the receiver \n");
#endif

	/* Receive any message from any task */
	buffer_id = pvm_recv(-1, -1);

	if (buffer_id < 0) {
	    printf("Error on receive in receiver\n");
	    exit(-1);
	}
	pvm_upkint( &p->prot.othertid, 1, 1 );
    }
}
예제 #25
0
int main (int argc, char **argv)
 
{
	int Finish,dip=65;
        int nz;                 /* number of migrated depth samples */
        int nxo,nx;             /* number of midpoints  */
        int iz,iw,ix,ix2,ix3,ixshot;     /* loop counters*/
        int ntfft;        	/* fft size*/
        int nw;              /* number of frequency*/
        int mytid,msgtype,rc,parent_tid;


        float dt=0.004,dz;         /*time and depth sampling interval*/
        float dw;            /*frequency sampling interval */
        float fw;            /* first frequency*/
        float w;              /* frequency*/
        float dx;               /* spatial sampling interval*/
        float **cresult;    /*output data*/
        float v1;
        float para;
        double kz2;
        float **vp,**v;
        complex cshift2;
        complex **cp,**cp1;  /* complex input,output         */

	/*get my and father pids*/
	mytid=pvm_mytid();
	parent_tid=pvm_parent();

	/*receive global parameters*/
	msgtype=PARA_MSGTYPE;	
	rc=pvm_recv(-1,msgtype);
	rc=pvm_upkint(&nxo,1,1);
	rc=pvm_upkint(&nz,1,1);
	rc=pvm_upkint(&dip,1,1);
        rc=pvm_upkfloat(&para,1,1);
	
	/*allocate space for velocity profile and receive velocity from father*/
        vp=alloc2float(nxo,nz);
        msgtype=VEL_MSGTYPE;
        rc=pvm_recv(-1,msgtype);
        rc=pvm_upkfloat(vp[0],nxo*nz,1);

	/*allocate space for the storage of partial image and zero it out now*/ 
        cresult = alloc2float(nz,nxo);
	for(ix=0;ix<nxo;ix++)
	for(iz=0;iz<nz;iz++)
	cresult[ix][iz]=0.0;

/*loop over shotgather*/
loop:

	/*receive parameters for each shot gather*/
        msgtype=PARA_MSGTYPE;
        rc=pvm_recv(parent_tid,msgtype);
	rc=pvm_upkint(&Finish,1,1);
	if(Finish==FinalDone)goto end;

 	rc=pvm_upkint(&ntfft,1,1);
        rc=pvm_upkint(&ix2,1,1);
        rc=pvm_upkint(&ix3,1,1);
	rc=pvm_upkint(&ixshot,1,1);

	nx=ix3-ix2+1;	

	rc=pvm_upkfloat(&dx,1,1);
	rc=pvm_upkfloat(&dz,1,1);
 	rc=pvm_upkfloat(&dw,1,1);
        rc=pvm_upkfloat(&dt,1,1);

	/*allocate space for velocity profile within the aperature*/
	v=alloc2float(nx,nz);

	for(iz=0;iz<nz;iz++)
	for(ix=0;ix<nx;ix++){
	v[iz][ix]=vp[iz][ix+ix2];
	}




	while(1){
		/*receive parameters and data for processing*/
		msgtype=DATA_MSGTYPE;
		rc=pvm_recv(parent_tid,msgtype);
		rc=pvm_upkint(&Finish,1,1);

		if(Finish==Done) {free2float(v);goto loop; }
		rc=pvm_upkfloat(&fw,1,1);

		rc=pvm_upkint(&nw,1,1);
		cp = alloc2complex(nx,nw);
		cp1 = alloc2complex(nx,nw);
		rc=pvm_upkfloat((float *)cp[0],nx*nw*2,1);
		rc=pvm_upkfloat((float *)cp1[0],nx*nw*2,1);



        /* loops over depth */
        for(iz=0;iz<nz;++iz){

	/*the imaging condition*/
/*	for(ix=0;ix<nx;ix++){
	for(iw=0,w=fw;iw<nw;w+=dw,iw++){
		complex tmp;
		float ratio=10.0;

		if(fabs(ix+ix2-ixshot)*dx<ratio*iz*dz)
		tmp=cmul(cp[iw][ix],cp1[iw][ix]);
		else tmp=cmplx(0.0,0.0);
		cresult[ix+ix2][iz]+=tmp.r/ntfft;
	}
	}
*/


/* anothe imaging condition, slightly different from the above one, but not quite
slow*/


        for(iw=0,w=fw;iw<nw;w+=dw,iw++){ 
		float kk=0.0;
		complex tmp;
		float ratio=1.5;
		if(dip<80)ratio=1.5;
		else ratio=1.5;
        
		for(ix=0;ix<nx;ix++){
		kk+=(pow(cp1[iw][ix].i,2.0)+pow(cp1[iw][ix].r,2.0))/nx;
		}       
                
		for(ix=0;ix<nx;ix++){
		tmp=cmul(cp[iw][ix],cp1[iw][ix]);

		if(fabs(ix+ix2-ixshot)*dx<ratio*iz*dz)

		tmp=crmul(tmp,1.0/(kk+1.0e-10));

		else tmp=cmplx(0.0,0.0);

		cresult[ix+ix2][iz]+=tmp.r/ntfft;

		}
		}


		/*get the average velocity*/
		v1=0.0;
                for(ix=0;ix<nx;++ix)
		{v1+=v[iz][ix]/nx;}
		
		/*compute time-invariant wavefield*/
/*                for(ix=0;ix<nx;++ix)
                for(iw=0,w=fw;iw<nw;w+=dw,++iw) {
                        kz2=-(1.0/v1)*w*dz;
                        cshift2=cmplx(cos(kz2),sin(kz2));   
                        cp[iw][ix]=cmul(cp[iw][ix],cshift2);
                        cp1[iw][ix]=cmul(cp1[iw][ix],cshift2);
                }
*/
		/*wave-propagation using finite-difference method*/
                fdmig( cp, nx, nw,v[iz],fw,dw,dz,dx,dt,dip,para);
                fdmig( cp1,nx, nw,v[iz],fw,dw,dz,dx,dt,dip,para);

		/*apply thin lens term here*/                                
                for(ix=0;ix<nx;++ix)
                for(iw=0,w=fw;iw<nw;w+=dw,++iw){
		float Wi=-dw;
		kz2=-(1.0/v[iz][ix])*dz;
/*			kz2=-(1.0/v[iz][ix]-1.0/v1)*w*dz;
			cshift2=cmplx(cos(kz2),sin(kz2));*/
			cshift2=cexp(cmplx(-Wi*kz2,w*kz2));
			cp[iw][ix]=cmul(cp[iw][ix],cshift2);
			cp1[iw][ix]=cmul(cp1[iw][ix],cshift2);
		}
                
}

/*finish a portion of the data, request more*/
pvm_initsend(PvmDataDefault);
pvm_pkint(&mytid,1,1);
msgtype=COM_MSGTYPE;
pvm_send(parent_tid,msgtype);
         
free2complex(cp);
free2complex(cp1);

}


end:

/*everything done,send back partial image and wait for signal to kill itself*/
pvm_initsend(PvmDataDefault);
pvm_pkfloat(cresult[0],nxo*nz,1);
msgtype=RESULT_MSGTYPE;
pvm_send(parent_tid,msgtype);
msgtype=COM_MSGTYPE;
pvm_recv(-1,msgtype);
pvm_exit();
exit(0);
}
예제 #26
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;
                                
}                               
예제 #27
0
int
main(int, char** argv) {
  int status = 0;
  int mytid = pvm_mytid();
  int masterid = pvm_parent();
  if(mytid < 0 || masterid < 0) {
    cerr << "\n" << argv[0] << ": Couldn't get slave/master IDs.  Aborting.\n";
    exit(1);
  }

  GA1DBinaryStringGenome genome(GENOME_LENGTH,GenomeEvaluator);
  GASteadyStateGA ga(genome);

  status = pvm_initsend(PvmDataDefault);
  status = pvm_send(masterid, MSG_READY);

  int done = 0;
  while(!done){
    int bufid = pvm_recv(-1, -1);
    int ival;
    if(bufid >= 0) {
      int bytes, msgtag, tid;
      status = pvm_bufinfo(bufid, &bytes, &msgtag, &tid);
      switch(msgtag) {
      case MSG_DONE:
	done = 1;
	break;

      case MSG_SET_POPULATION_SIZE:
	ival = gaDefPopSize;
	status = pvm_upkint(&ival, 1, 1);
	ga.populationSize(ival);
	break;

      case MSG_INITIALIZE:
	ga.initialize();
	break;

      case MSG_STEP:
	ival = 0;
	status = pvm_upkint(&ival, 1, 1);
	for(int i=0; i<ival; i++)
	  ga.step();
	ival = ga.generation();
	  status = pvm_initsend(PvmDataDefault);
	status = pvm_pkint(&ival, 1, 1);
	status = pvm_send(masterid, MSG_STEP_COMPLETE);
	break;

      case MSG_INCOMING_MIGRATION:
	RecvMigration(ga);
	break;

      case MSG_SEND_MIGRATION:
	{
	  int toid = 0, count = 0;
	  status = pvm_upkint(&toid, 1, 1);
	  status = pvm_upkint(&count, 1, 1);
	  SendMigration(toid, ga, count);
	}
	break;

      case MSG_SEND_POPULATION:
	SendPopulation(masterid, ga.population());
	break;

      case MSG_SEND_STATISTICS:
	SendStatistics(masterid, ga.statistics());
	break;

      default:
	cerr << argv[0] << ": unknown msgtag: " << msgtag << "\n";
	break;
      }
    }
    else {
      cerr << argv[0] << ": error from pvm_recv: " << bufid << "\n";
    }
  }

  pvm_exit();
  return 0;
}