Exemplo n.º 1
0
int main(void){
    int tid; /*this task id */
    int bufid, master, bytes, msgtag, source;
    char * graph_text = NULL;
    int **matrix;
    int degree, edges;
    int len;
    int i;
    int greycodeLength;
    
    tid = pvm_mytid();          /*enroll in pvm */
    master = pvm_parent();      /*get the master id */

    while (1){    
        /*Get the first graph */
        pvm_initsend(PvmDataDefault);
        pvm_pkstr("");                                        /*Just put something in the buffer */
        pvm_send(master, MSGREQTASK);                         /* Request a task */
        bufid = pvm_recv(master, MSGTASK);                    /* Get the task */
        pvm_bufinfo(bufid, &bytes, &msgtag, &source);  /* Get the size of the text */
        graph_text = malloc(bytes);                           
        pvm_upkstr(graph_text);                               /* Unpack the text */

        len = strlen(graph_text);
        if(graph_text[len - 1] == '\n')
            graph_text[len - 1] = '\0';
            

        matrix = create_matrix(graph_text, &degree);          /*Generate the appropriate matrix */
        populate_matrix(graph_text, matrix, &edges, degree);

        greycodeLength = 1 << degree;
        // Initialize code (where the greycode is stored)
        int * vals = calloc(2 * greycodeLength, sizeof(int));
        int ** code = malloc(greycodeLength * sizeof(int *)); 

       for(i = 0; i < greycodeLength; i++){                     /*assign rows within the allocated space */ 
          code[i] = vals + i*2;
        }
	
        /*** DO GREYCODE ALGORITHM ON THE MATRIX ***/
        if(greycode(degree, matrix, code) == 1){                      /*If we found a code */
            pvm_initsend(PvmDataDefault);
            pvm_pkstr(graph_text);
            pvm_send(master, MSGCODE);
        } else{                                               /*Didnt find a code */
            pvm_initsend(PvmDataDefault);
            pvm_pkstr(graph_text);
            pvm_send(master,MSGNOCODE);
        }

        destroy_matrix(matrix);                               /* Free the memory associated with the matrix */
        destroy_matrix(code);
	    free(graph_text);
    }
 
    pvm_exit();
    exit(0);

}
Exemplo n.º 2
0
void SendBorderTime(BOOL leftest, BOOL rightest)
{
  BorderTimeDesc *bt;
  int nbt = 0, i, dff;
  for (bt = bordertime; bt; bt = bt->next)
    nbt += (bt->section != WEST_BORDER || leftest)  &&
           (bt->section != EAST_BORDER || rightest);
  pvm_pkint(&nbt, 1, 1);
  for (bt = bordertime; bt; bt = bt->next)  {
    if ((bt->section == WEST_BORDER && !leftest)  ||
        (bt->section == EAST_BORDER && !rightest))  continue;
    pvm_pkint((int *)&bt->vartype, 1, 1);
    pvm_pkint((int *)&bt->section, 1, 1);
    pvm_pkint(&bt->bigdim, 1, 1);
    pvm_pkint(&bt->ntime, 1, 1);
    pvm_pkint(&bt->itime, 1, 1);
    pvm_pkint(&bt->cdfid, 1, 1);
    pvm_pkint(&bt->vid, 1, 1);
    pvm_pkstr((char *)bt->actualvar.name);
    pvm_pkint((int *)&bt->actualvar.v.et, 1, 1);
    pvm_pkushort(&bt->actualvar.dims, 1, 1);
    pvm_pkint((int *)&bt->actualvar.storetype, 1, 1);
    pvm_pkint(&bt->actualvar.id, 1, 1);
    pvm_pkint(&bt->actualvar.ncoord, 1, 1);
    pvm_pkint((int *)&bt->nextvar.v.et, 1, 1);
    pvm_pkushort(&bt->nextvar.dims, 1, 1);
    pvm_pkint((int *)&bt->nextvar.storetype, 1, 1);
    pvm_pklong(bt->timetable, bt->ntime, 1);
    pvm_pkuint((unsigned *)bt->coords, 4, 1);
    for (i = 0; i < 4; i++)  {
      dff = bt->dimptr[i] - bt->coords;
      pvm_pkint(&dff, 1, 1);
    }
  }
}
Exemplo n.º 3
0
int send_str(char *str)
{
   int info;

   PVM_FUNC(info, pvm_pkstr(str));

   return(info);
}
Exemplo n.º 4
0
/*Function: get_task
 * Given a taskid of the task requesting a new graph, a graph will be sent off of the queue
 * taskid: the id of the requesting task that needs a new graph
*/
void send_task(int taskid){
    struct entry * task;
    task = TAILQ_FIRST(&head);
    TAILQ_REMOVE(&head, task, entries); /*Pop from the queue */
    pvm_initsend(PvmDataDefault);                 /*Clear the buffer */
    pvm_pkstr(task->graph_text);
    pvm_send(taskid, MSGTASK);
}
Exemplo n.º 5
0
int BBSClient::get(const char* key, int type) {
#if debug
printf("BBSClient::get |%s| type=%d\n", key, type);
fflush(stdout);
#endif
	int bufid, nbyte, msgtag, tid, index;
	pvm_initsend(PvmDataDefault);
	pvm_pkstr((char*)key);
	return get(type);
}
Exemplo n.º 6
0
void SendStr(char * str, int tid, int MsgType)
{
  int info;

  info = pvm_initsend(PvmDataDefault);
  if (info) 
  {
     pvm_pkstr(str);
     pvm_send(tid, MsgType);
  }
  else
  {
     fprintf(stderr, "Problems with SendStr : Message type %d\n", MsgType);
  }
}
Exemplo n.º 7
0
void SendMessagetoMasterTyp(char* message,int typ){
	struct timeval tv ;

	pvm_initsend(PvmDataDefault);
	pvm_pkint(&typ, 1, 1);

	gettimeofday(&tv,NULL);
	pvm_pklong(&tv.tv_sec,1,1);
	pvm_pklong(&tv.tv_usec,1,1);

	pvm_pkstr(message);	

	pvm_send(tid_master, MSG_DBG);

}
Exemplo n.º 8
0
void BroadStr(char *str, int tids[], int ntids, int MsgType)
{
  int info;

  info = pvm_initsend(PvmDataDefault);
  if (info) 
  {
     pvm_pkstr(str);
     pvm_mcast(tids,ntids, MsgType);
  }
  else
  {
     fprintf(stderr, "Problems with BroadStr : Message type %d\n", MsgType);
  }
}
Exemplo n.º 9
0
main()
{
        int ptid;
        char greetings[100];

        ptid=pvm_parent(); /*get tid of task that started me*/
        strcpy(greetings,"Hello world from ");
        gethostname(greetings + strlen(greetings));

        pvm_initsend(PvmDataDefault); /*initialize send buffer*/
        pvm_pkstr(greetings); /*XDR encode string into send buffer*/
        pvm_send(ptid,1);

        pvm_exit(); /*disconnect from the PVM*/
        exit(0);
}
Exemplo n.º 10
0
/* add self to worker list */
void hello() {
  int i,b,n;
  pvmtaskinfo *ta;
  pvm_tasks(0,&n,&ta);
  for (i=0;i<n;i++)
    if (!strcmp(ta[i].ti_a_out,"kalah")) {
      pvm_initsend(0);
      pvm_pkstr(host);
      pvm_send(ta[i].ti_tid,TAG_HELLO);
      break;
      } 
  b = pvm_recv(-1,TAG_WORKERS); 
  if (b < 0)
    die("Failed to receive worker list\n");
  p_handle(b);
  }
Exemplo n.º 11
0
void diag_msg(int mstrtid, int mytid, char *str) {
	struct timeval current_time;
	time_t logTime = time(NULL);
	char *timeStr =  asctime(localtime(&logTime));
	gettimeofday(&current_time, NULL);
	timeStr[strlen(timeStr)-6] = '\0';
	timeStr = timeStr + 11;

	char message[200];
	sprintf(message, "(%d) %s.%zu: %s", mytid, timeStr, current_time.tv_usec, str);
	// logEvent(mytid, message);

	pvm_initsend(PvmDataDefault);
	pvm_pkstr(message);
	pvm_send(mstrtid, MSG_DIAG);
}
Exemplo n.º 12
0
main()
{
	int ptid;
	char buf[100];

	ptid = pvm_parent();

	strcpy(buf, "hello, world from ");
	gethostname(buf + strlen(buf), 64);

	pvm_initsend(PvmDataDefault);
	pvm_pkstr(buf);
	pvm_send(ptid, 1);

	pvm_exit();
	exit(0);
}
Exemplo n.º 13
0
void BBSClient::post(const char* key) {
#if debug
printf("BBSClient::post |%s|\n", key);
fflush(stdout);
#endif
	int index, os;
	os = pvm_setsbuf(pvm_mkbuf(PvmDataDefault));
	pvm_pkstr((char*)key);
#if defined(HAVE_PKMESG)
	pvm_pkmesg(os);
	index = pvm_send(sid_, POST);
#else
	pvm_send(sid_, CRAY_POST);
	os = pvm_setsbuf(os);
	index = pvm_send(sid_, CRAY_POST);
#endif
	pvm_freebuf(os);
	if (index < 0) {perror("post");}
}
Exemplo n.º 14
0
void BBSClient::pkstr(const char* s) {
	int len = strlen(s);
	if( pvm_pkint(&len, 1, 1)) { perror("pkstr length"); }
	if( pvm_pkstr((char*)s)) { perror("pkstr string"); }
}
Exemplo n.º 15
0
main() {
    int mytid, tid_master;
    char slave_name[NAMESIZE];
    char current_pass[NAMESIZE];
    char hash[NAMESIZE];
    char current_hash[NAMESIZE];
    char znalazl = 0 ;
    gethostname(slave_name, NAMESIZE+1);

    mytid = pvm_mytid();

    int inst = pvm_joingroup(GRP) ;

    int tid = pvm_gettid(GRP ,inst);

    int info = pvm_barrier(GRP,SLAVENUM + 1);

    pvm_recv( -1, MSG_MSTR );
    pvm_upkint(&tid_master, 1, 1 );
    pvm_upkstr(hash);
    //pvm_upkint(&k, 1, 1 );

    char poczatek = 97 + inst-1;
    char c1,c2,c3,c4,c5;
    for(c1 = poczatek ; c1 <= 'z' ; c1++) {
        for(c2 = 'a' ; c2 <= 'z' ; c2++) {
            for(c3 = 'a' ; c3 <= 'z' ; c3++) {
                for(c4 = 'a' ; c4 <= 'z' ; c4++) {
                    for(c5 = 'a' ; c5 <= 'z' ; c5++) {
                        current_hash[0] = c1 ;
                        current_hash[1] = c2 ;
                        current_hash[2] = c3 ;
                        current_hash[3] = c4 ;
                        current_hash[4] = c5 ;
                        current_hash[6] = 0 ;
                        current_hash = crypt(current_pass,"aa");
                        if(strcmp(current_hash,hash)==0) {
                            znalazl = 1;
                            break;
                        }
                        if(znalazl)
                            break ;
                    }
                    if(znalazl)
                        break ;
                }
                if(znalazl)
                    break ;
            }
            if(znalazl)
                break ;
        }
        if(znalazl)
            break ;
    }

    pvm_initsend(PvmDataDefault);
    //pvm_pkint(&k, 1, 1);
    pvm_pkstr(slave_name);
    if(znalazl) {
        pvm_pkstr("znalazlem");
    }
    else {
        pvm_pkstr("nie znalazlem");
    }
    pvm_pkstr(slave_name);
    pvm_send(tid_master, MSG_SLV);


    pvm_exit();




}
Exemplo n.º 16
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;
}
Exemplo n.º 17
0
int main(int argc, char** argv){
  int parent_tid = pvm_parent();
  int my_tid = pvm_mytid();
  DEBUGA("[TID  %d] Slave starting ...",my_tid);
  /* Checking number of arguments */
  if(argc<=3){
    printf("Error in arguments");
    exit(1);
  }


  /* Getting password from arguments */
  int number_of_threads = atoi(argv[3]);
  int posi = atoi(argv[4]);
  int pass_size = atoi(argv[1]);

  char * password = malloc(sizeof(char)*(pass_size+1));
  password[0] = '\0';
  strncat(password,argv[2],pass_size);
  password[pass_size] = '\0';

  DEBUGA("[TID  %d] Password %s Size %d",my_tid,password,pass_size);


  char * temp_password = malloc(sizeof(char)*(pass_size+1));
  char * interval_start = malloc(sizeof(char)*(pass_size+1));
  char * interval_end = malloc(sizeof(char)*(pass_size+1));
  char * recv_buffer = malloc(sizeof(char)*MAX_SIZE);
  recv_buffer[0] = '\0';
  unsigned long long interval_size;

  int buf_size,mes_tag,mes_tid,buf_id;

    
  /* Ask parent for new interval */
  pvm_initsend(PvmDataDefault);
  pvm_pkint(&my_tid,1,1);
  pvm_send(parent_tid,NEED_INTERVAL);
  buf_id = pvm_recv(parent_tid,-1);
  pvm_bufinfo(buf_id,&buf_size,&mes_tag,&mes_tid);

  if(mes_tag == NEW_INTERVAL){
    pvm_upkstr(recv_buffer);
  }
  else if(mes_tag == NO_NEW_INTERVAL){
    exit(1);
  }
  else{
    exit(1);
  }
 
  /* Extract data from buffer */
  interval_start[0] = '\0';
  interval_end[0] = '\0';
  temp_password[0]='\0';
  strncpy(interval_start,recv_buffer,pass_size);
  interval_start[pass_size] = '\0';
  strncpy(interval_end,recv_buffer+pass_size,pass_size);
  interval_end[pass_size] = '\0';
  
  pthread_mutex_lock(&mutex_i_manager);
  init_interval_manager(&i_manager,
			interval_start,
			interval_end,
			password,
			posi);
  pthread_mutex_unlock(&mutex_i_manager);


  /* Creating threads ... */
  pthread_t * threads = malloc(sizeof(pthread_t)*number_of_threads);
  pthread_attr_t attr;
  int c_thread = 0;
  for(c_thread = 0; c_thread < number_of_threads ; ++c_thread){
    pthread_create(&threads[c_thread],&attr,find_password_thread,(void*)NULL);
  }

    
  while(1){
    

    pthread_mutex_lock(&mutex_action);
    pthread_mutex_unlock(&mutex_slave_waiting);
    pthread_cond_wait(&cond_action,&mutex_action);
    pthread_mutex_lock(&mutex_slave_waiting);

    if(action == NEW_INTERVAL){
      pvm_initsend(PvmDataDefault);
      pvm_pkint(&my_tid,1,1);
      pvm_send(parent_tid,NEED_INTERVAL);
      buf_id = pvm_recv(parent_tid,-1);
      pvm_bufinfo(buf_id,&buf_size,&mes_tag,&mes_tid);
      
      if(mes_tag == NEW_INTERVAL){
	pvm_upkstr(recv_buffer);
	interval_start[0] = '\0';
	interval_end[0] = '\0';
	strncpy(interval_start,recv_buffer,pass_size);
	interval_start[pass_size] = '\0';
	strncpy(interval_end,recv_buffer+pass_size,pass_size);
	interval_end[pass_size] = '\0';
	DEBUGA("New interval start interval : %s end interval : %s",interval_start,interval_end);
	pthread_mutex_lock(&mutex_i_manager);
	set_new_interval(&i_manager,interval_start,interval_end);
	pthread_mutex_unlock(&mutex_i_manager);

      }
      else if(mes_tag == NO_NEW_INTERVAL){
	
      }
      else{
      }
    }
    else if (action == FOUND_PASSWORD){
      pthread_mutex_lock(&mutex_f_password);
      pthread_mutex_lock(&mutex_f_c_password);
      
      DEBUGA("[TID  %d] Found Password",my_tid);
      pvm_initsend( PvmDataDefault );
      pvm_pkstr(found_char_password);
      pvm_send(parent_tid,FOUND_PASSWORD);
      pthread_mutex_unlock(&mutex_f_password);
      pthread_mutex_unlock(&mutex_f_c_password);
      break;

    }
    pthread_mutex_unlock(&mutex_action);
    

  }


 
  
  pvm_send(parent_tid,CHILD_TERMINATE);
  DEBUGA("[TID  %d] Terminating slave",my_tid);

  free(password);
  free(temp_password);
  free(interval_start);
  free(interval_end);
  free(recv_buffer);

  return EXIT_SUCCESS;
}
Exemplo n.º 18
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();
}
Exemplo n.º 19
0
void BBSDirect::pkstr(const char* s) {
	int len = strlen(s);
//	printf("pkstr |%s| into %d\n", s,  pvm_getsbuf());
	if( pvm_pkint(&len, 1, 1)) { perror("pkstr length"); }
	if( pvm_pkstr((char*)s)) { perror("pkstr string"); }
}
Exemplo n.º 20
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;
}