Пример #1
0
void insert_list(My402List * list, My402TransData * data)
{
	if(My402ListEmpty(list))
		(void)My402ListAppend(list, (void*)data);
	else
	{
		My402ListElem * elem = My402ListFirst(list);
		while(elem)
		{
			My402TransData * temp = (My402TransData *)(elem -> obj);
			if(temp -> timestamp < data -> timestamp)
			{
				elem = My402ListNext(list, elem);
				if(!elem)
					(void)My402ListAppend(list, (void*)data);
			}
			else if(temp -> timestamp > data -> timestamp)
			{
				(void)My402ListInsertBefore(list, (void*)data, elem);
				break;
			}
			else
				print_error("two identical timestamp");
		}
	}
}
Пример #2
0
/* Process the pakcets in Q1 and transfer to Q2 when enough tokens */
void ProcessPacket(){
    My402ListElem *find = NULL;
    Packet_desc *p = NULL;
    
    find=My402ListFirst(&Q1_node);
    
    if(find->obj == NULL){
        fprintf(stderr,"Error: Obj is NULL");
        pthread_exit(0);
    }
    
    p = (Packet_desc*)find->obj;
    
    
    if(p->tokens <= token_limit){
        // move this to Q2
        
        token_limit -= p->tokens;
        
        // total time in Q1
        
        p->total_Q1_time = GetMTimeOfDay()- p->Q1_time_enters;
        
        
        fprintf(stdout, "%012.3lfms: p%d leaves Q1, time in Q1 = %.3lfms, tokens bucket now has %d token\n",GetMTimeOfDay(),p->name_ID,p->total_Q1_time,token_limit);
        
        
        if(My402ListEmpty(&Q2_node)){
            // signal the condition about the queue not empty
            p->Q2_time_enters = GetMTimeOfDay();
            // Q2_time_enters[p->name_ID] = GetMTimeOfDay();
            fprintf(stdout, "%012.3lfms: p%d enters Q2\n",GetMTimeOfDay(),p->name_ID);
            
            My402ListAppend(&Q2_node, (void*)p);
            curr_q2_size = 1;
            /* signal the condition variable queue*/
            pthread_cond_signal(&serverQ);
            find = My402ListFind(&Q1_node, (void*)p);
            My402ListUnlink(&Q1_node, find);
            
        }else{
            p->Q2_time_enters = GetMTimeOfDay();
            
            //   Q2_time_enters[p->name_ID] = GetMTimeOfDay();
            
            fprintf(stdout, "%012.3lfms: p%d enters Q2\n",GetMTimeOfDay(),p->name_ID);
            
            My402ListAppend(&Q2_node, (void*)p);
            /* gaurd set true */
            curr_q2_size = 1;
            find = My402ListFind(&Q1_node, (void*)p);
            My402ListUnlink(&Q1_node, find);
            
        }
        
    }
}
Пример #3
0
int sortInsert(My402List *list, ListEntry *Entry)
{
    My402ListElem *temp;
    ListEntry *tempobj;
    temp = My402ListNext(list, &list->anchor);

    while(temp){
        tempobj = (ListEntry *) temp->obj;
        if(Entry->timestamp == tempobj->timestamp) {
            fprintf(stderr, "Transactions have Identical timestamp %ld\n", Entry->timestamp);
            return 0;
        }
        if(Entry->timestamp < tempobj->timestamp) {
            if(!My402ListInsertBefore(list, Entry, temp)){
                return 0;
            }
            return 1;
        }
        temp = My402ListNext(list, temp);
    }
    if(!My402ListAppend(list, Entry)){
        return 0;
    }
    return 1;
}
Пример #4
0
static
void BubbleForward(My402List *pList, My402ListElem **pp_elem1, My402ListElem **pp_elem2)
    /* (*pp_elem1) must be closer to First() than (*pp_elem2) */
{
    My402ListElem *elem1=(*pp_elem1), *elem2=(*pp_elem2);
    void *obj1=elem1->obj, *obj2=elem2->obj;
    My402ListElem *elem1prev=My402ListPrev(pList, elem1);
/*  My402ListElem *elem1next=My402ListNext(pList, elem1); */
/*  My402ListElem *elem2prev=My402ListPrev(pList, elem2); */
    My402ListElem *elem2next=My402ListNext(pList, elem2);

    My402ListUnlink(pList, elem1);
    My402ListUnlink(pList, elem2);
    if (elem1prev == NULL) {
        (void)My402ListPrepend(pList, obj2);
        *pp_elem1 = My402ListFirst(pList);
    } else {
        (void)My402ListInsertAfter(pList, obj2, elem1prev);
        *pp_elem1 = My402ListNext(pList, elem1prev);
    }
    if (elem2next == NULL) {
        (void)My402ListAppend(pList, obj1);
        *pp_elem2 = My402ListLast(pList);
    } else {
        (void)My402ListInsertBefore(pList, obj1, elem2next);
        *pp_elem2 = My402ListPrev(pList, elem2next);
    }
}
Пример #5
0
 int  My402ListInsertAfter(My402List* list, void* obj, My402ListElem* elem)
 {
	 My402ListElem* newItem = NULL;
	 if(NULL == elem || My402ListLast(list) == elem)
		 return My402ListAppend(list,obj);
	 else
	 {
	 newItem = (My402ListElem*)malloc(sizeof(My402ListElem));
		if(NULL == newItem) 
		{
			//print error
			return FALSE;
		}
		newItem->obj = obj;

		newItem->next = elem->next;
		elem->next->prev = newItem;

		newItem->prev = elem;
		elem->next = newItem;
		++list->num_members;
		return TRUE;
	 }
	return FALSE;	 
 }
int  My402ListInsertAfter(My402List *list, void *obj, My402ListElem *elem){
    if(list != NULL){
		if(elem == NULL){
		    if(My402ListAppend(list, obj))
		        return 1;
		    else
		        return 0;
		}
		else{
		    My402ListElem *new_elem = (My402ListElem *)malloc(sizeof(My402ListElem));
		    if(new_elem == 0 || new_elem == NULL){
		        return 0;
		    }   
		    else{
		        new_elem -> obj = obj;
		        elem -> next -> prev = new_elem;
		        new_elem -> next = elem -> next;
		        elem -> next = new_elem;
		        new_elem -> prev = elem;
		        list -> num_members++;
		        return 1;
		    }
		}
	}
	else
    	return 0;
}
Пример #7
0
extern int  My402ListInsertAfter(My402List*list, void*item, My402ListElem*elem)
{
	if(elem==NULL)
	{
		int x;
		x=My402ListAppend(list, item);
		if(x==1)
			return(1);
		else
			return(0);//not req
	}
	else
	{
		My402ListElem *curr=NULL;//element that is to be inserted
		curr=malloc(sizeof(struct tagMy402ListElem));
		curr->obj=item;
		curr->prev=elem;
		curr->next=elem->next;
		elem->next->prev=curr;
		elem->next=curr;
		list->num_members++;
		return(1);
	}
	return(0);
}
static
void CreateTestList(My402List *pList, int num_items)
{
    int i=0;

    for (i=0; i < num_items; i++) {
        (void)My402ListAppend(pList, (void*)i);
    }
}
static
void CopyTestList(My402List *pListFrom, My402List *pListTo)
{
    My402ListElem *elem=NULL;

    for (elem=My402ListFirst(pListFrom); elem != NULL; elem=My402ListNext(pListFrom, elem)) {
        (void)My402ListAppend(pListTo, elem->obj);
    }
}
Пример #10
0
/* Enque the packet in Q1 when arrived */
void EnquePacket(Packet_desc *p){
    //   int j = i+1;
    p->Q1_time_enters = GetMTimeOfDay(); //lavish
    
    //Q1_time_enters[p->name_ID] = GetMTimeOfDay();
    fprintf(stdout, "%012.3lfms: p%d enters Q1\n",GetMTimeOfDay(), p->name_ID);
    
    My402ListAppend(&Q1_node, (void*)p);
    
}
static
void RandomShuffle(My402List *pList, int num_items)
{
    int i=0;
    My402List list2;
    My402ListElem *elem=NULL;

    memset(&list2, 0, sizeof(My402List));
    (void)My402ListInit(&list2);

    for (i=0; i < num_items; i++) {
        int j=0, idx=0, num_in_list=num_items-i;
        void *obj=NULL;

        idx = RandomIndex(num_in_list);
        for (elem=My402ListFirst(pList); elem != NULL; elem=My402ListNext(pList, elem)) {
            if (j == idx) {
                break;
            }
            j++;
        }
        if (elem == NULL) {
            fprintf(stderr, "Unrecoverable error in RandomShuffle().\n");
            exit(1);
        }
        obj = elem->obj;
        My402ListUnlink(pList, elem);
        (void)My402ListAppend(&list2, obj);
    }
    if (!My402ListEmpty(pList)) {
        fprintf(stderr, "List not empty in RandomShuffle().\n");
        exit(1);
    }
    for (elem=My402ListFirst(&list2); elem != NULL; elem=My402ListNext(&list2, elem)) {
        (void)My402ListAppend(pList, elem->obj);
    }
    My402ListUnlinkAll(&list2);
}
int  My402ListInsertAfter(My402List* list, void* new_obj, My402ListElem* elem)
{
	// snaity check
	if (!elem) return My402ListAppend(list, new_obj);	
	My402ListElem* temp_elem = (My402ListElem*) malloc (sizeof(My402ListElem));
	if (!temp_elem) return FALSE;
	temp_elem->prev = elem;
	temp_elem->next = elem->next;
	temp_elem->obj = new_obj;	
	(elem->next)->prev = temp_elem;
	elem->next = temp_elem;
	list->num_members ++;
	return TRUE;
}
int  My402ListInsertAfter(My402List *pList, void *obj, My402ListElem *elem){
	if(elem == NULL) return My402ListAppend(pList, obj);
	else{
		My402ListElem *temp = (My402ListElem *)malloc(sizeof(My402ListElem));
		if(temp == NULL) return FALSE;
		temp->obj = obj;
		temp->next = elem->next;
		temp->prev = elem;
		elem->next->prev = temp;
		elem->next = temp;
	}
	pList->num_members++;
	return TRUE;
}
Пример #14
0
static
void CreateTestList(My402List *pList, TransactionElem *tranElement)
{
		My402ListElem *listElem = My402ListFirst(pList);
		int i = 0;
		for(;i<pList->num_members;i++) {
			if(tranElement->eleTime != (unsigned int)(((TransactionElem *)listElem->obj)->eleTime)) {
			listElem = My402ListNext(pList,listElem);
			} else {
					fprintf(stderr,"Error: Identical Timestamps cannot be added to the list");
					PrintErrorMessage();
			}
		}
        (void)My402ListAppend(pList, (void*)tranElement);
}
Пример #15
0
/**
 * @brief Create sender list
 *
 */
void create_list(char *data_ptr, My402List *list, const char *list_type){
    // Initialize the data list
    if (My402ListInit(list)==0){
        exit(1);
    }

    // Iterate and add nodes with seq_num and mem address
    vlong seq_num = 0;
    for (;seq_num<globals.config.total_size; seq_num += globals.config.packet_size){
        struct node *data_node = malloc(sizeof(struct node));
        data_node->seq_num = seq_num;
        data_node->mem_ptr = data_ptr + seq_num;
        // To handle scenario where the last packet is of size less then
        // required
        vlong size = globals.config.total_size - seq_num > globals.config.packet_size ? globals.config.packet_size : globals.config.total_size - seq_num;
        // size in bytes
        data_node->size = size;

        My402ListElem *link_node;
        if (My402ListAppend(list , data_node, &link_node)==0)
	    list_error("Append Failed");

        //DBG("MEM PTR = %p, SEQ_NUM = %llu", data_node->mem_ptr, data_node->seq_num);

        // Check if DATA or NACK list
        // Add the linked list node pointer to the hashmap node
        if (strcmp(list_type, DATA) == 0) {
            // DATA list
            hashed_link *hash_node = malloc(sizeof(hashed_link));
            hash_node->seq_num = data_node->seq_num;
            hash_node->data_node_ptr = link_node;
            add_hashl(hash_node);
        }
        else {
            // NACK list
            hashed_link *hash_node = (hashed_link *)(find_hashl(data_node->seq_num));
            if (!hash_node) {
                DBG("This should never happen");
                exit(1);
            }
            hash_node->nack_node_ptr = link_node;
        }
    }
}
Пример #16
0
int My402ListInsertAfter(My402List * list, void * data, My402ListElem * elem)
{
    if(elem == NULL)
        return My402ListAppend(list, data);
    else
    {
        My402ListElem * new_elem = (My402ListElem *)malloc(sizeof(My402ListElem));
        if(!new_elem)
            return 0;
        My402ListElem * next = elem -> next;
        new_elem -> obj = data;
        next -> prev = new_elem;
        elem -> next = new_elem;
        new_elem -> next = next;
        new_elem -> prev = elem;
        list -> num_members++;
        return 1;
    }
}
Пример #17
0
// Insert After specified list Element
int  My402ListInsertAfter(My402List* myList, void* elem, My402ListElem* listElement) { 
	My402ListElem *newElement = NULL;
	newElement = (My402ListElem *)malloc(sizeof(My402ListElem));
	if(newElement != NULL) {
		if(listElement != NULL) {
			newElement->next = listElement->next;
			listElement->next->prev = newElement;
			listElement->next = newElement;
			newElement->prev = listElement;
			newElement->obj = elem;
			myList->num_members++;
			
			return TRUE;
		} else {
			return My402ListAppend(myList, elem);	
		}
	} 
	return FALSE;	
}
Пример #18
0
/**
 * @brief Append node for retransmission
 * NOT USED
 */
void add_retransmission_node(vlong *retrans_list, int num_retrans){
    // Iterate the retrans_list
    int i;
    for (i=0;i<num_retrans;i++){
        vlong seq_num = retrans_list[i];
        DBG("Add node = %llu", seq_num);
        hashed_link *hash_node = (hashed_link *)(find_hashl(seq_num));

        // Create a duplicate node
        struct node *data_node = malloc(sizeof(struct node));
        data_node->seq_num = seq_num;
        data_node->mem_ptr = ((struct node*)((hash_node->data_node_ptr)->obj))->mem_ptr;
        data_node->size = ((struct node*)((hash_node->data_node_ptr)->obj))->size;

        // Append the duplicate node to the end of the data list.
        My402ListElem *link_node;
        if (My402ListAppend(&globals.datal , data_node, &link_node)==0)
            list_error("Error in appending to list");
    }
}
Пример #19
0
void move_packet_q1_to_q2(struct command_line_args *object, My402ListElem *elem, struct packet *p)
{
	double time;
	int isEmpty = 0;
	My402ListUnlink(&Q1PacketList, elem);
	gettimeofday(&(p->Q1leaves),NULL);
	time = (TIME_IN_USEC(p->Q1leaves) - TIME_IN_USEC(GlobalStartTime))/1000;
	p->time_in_Q1 = (TIME_IN_USEC(p->Q1leaves) - TIME_IN_USEC(p->Q1timestamp))/1000;
	LOG(stdout, "%012.3fms: p%d leaves Q1, time in Q1 = %.3fms, token bucket now has %d token%c\n",time,p->packet_id,p->time_in_Q1,tokens_in_bucket,(tokens_in_bucket > 1 ?'s':' '));	
	q1_temp_count++;
		
	isEmpty = My402ListEmpty(&Q2PacketList);
	My402ListAppend(&Q2PacketList, p);
	gettimeofday(&(p->Q2timestamp),NULL);
	time = (TIME_IN_USEC(p->Q2timestamp) - TIME_IN_USEC(GlobalStartTime))/1000;
	LOG(stdout, "%012.3fms: p%d enters Q2\n",time,p->packet_id);	
	if(isEmpty)
		pthread_cond_signal(&is_q2_empty);
		
}
Пример #20
0
int  My402ListInsertAfter(My402List* q, void* x, My402ListElem* n)
{


    if (n==NULL)
    {
        return My402ListAppend(q,x);

    }
    My402ListElem* t = NULL;
    My402ListElem* temp1 = NULL;
    temp1 = (My402ListElem*)malloc(sizeof(My402ListElem));
    t = (My402ListElem*)malloc(sizeof(My402ListElem));

    if (temp1==NULL)
    {
        return FALSE;
    }

    //else
    //{

    temp1->obj= x;

    t = n->next;

    n->next=temp1;
    temp1->next=t;
    t->prev=temp1;
    temp1->prev=n;



    //(temp1->next)->prev=temp1;
    //}

    q->num_members++;
    return TRUE;

}
Пример #21
0
/**
 * @brief Create list
 *        recv_data_list
 *        recv_nack__list
 *        only sequence number is added
 */
void create_recv_list(My402List *list, const char *list_type){
    // Initialize the data list
    if (My402ListInit(list)==0){
        exit(1);
    }

    // Iterate and add nodes with seq_num and mem address
    vlong seq_num = 0;
    for (;seq_num<globals.config.total_size; seq_num += globals.config.packet_size){
        struct node *data_node = malloc(sizeof(struct node));
        data_node->seq_num = seq_num;
        data_node->mem_ptr = NULL;

        My402ListElem *link_node;
        if (My402ListAppend(list , data_node, &link_node)==0)
	    list_error("Append Failed");

        // Check if DATA or NACK list
        // Add the linked list node pointer to the hashmap node
        if (strcmp(list_type, DATA) == 0) {
            // DATA list
            hashed_link *hash_node = malloc(sizeof(hashed_link));
            hash_node->seq_num = data_node->seq_num;
            hash_node->data_node_ptr = link_node;
            add_hashl(hash_node);
        }
        else {
            // NACK list
            hashed_link *hash_node = (hashed_link *)(find_hashl(data_node->seq_num));
            if (!hash_node) {
                DBG("This should never happen");
                exit(1);
            }
            hash_node->nack_node_ptr = link_node;
        }
    }
}
Пример #22
0
 extern int  My402ListInsertAfter(My402List* List, void* insData, My402ListElem* givenNode)
{

   My402ListElem *newNode = (My402ListElem *) malloc(sizeof(My402ListElem));
   if(newNode != NULL)
    {
        newNode->obj = insData;
        if(givenNode == NULL)
            {
                return My402ListAppend(List,insData);
            }
        else
            {
                My402ListElem *nextNode = givenNode->next;//BE CAREFULL
                givenNode->next = newNode;
                newNode->next = nextNode;
                nextNode->prev = newNode;
                newNode->prev = givenNode;
                (List->num_members)++;
                return TRUE;
            }
    }
     return FALSE;
}
Пример #23
0
  int  My402ListInsertAfter(My402List* list, void* obj, My402ListElem* element) {
//if element is NULL then it is same as append
short int result=0;
if(element==NULL){
result=My402ListAppend(list,obj);
return result;
}
else {
My402ListElem *newelement;
newelement=(My402ListElem *)malloc(sizeof(My402ListElem));
if(newelement){
element->next->prev=newelement;
newelement->next=element->next;
element->next=newelement;
newelement->prev=element;
newelement->obj=obj;
list->num_members++;
return TRUE;
}
else
return FALSE;
}

}
Пример #24
0
void DoSort(FILE *fp)
{
   /*
     Step1 a
     Open the file and generate linked list
   */
   trnx *t;
   char line[BUFFER];
   char *tokens;
   char *op,*timeval,*amt,*description;
   int errCheck = 1;
   /*
    Generate a list and Initialise it
   */
   My402List list;
   memset(&list,0,sizeof(My402List));

   (void)My402ListInit(&list);
   /*
   */
   fgets(line,BUFFER,fp);
   while (!feof(fp))
   {
     /*
       Perform the necessary error checks for the line
     */
     errCheck = errorCheckLine(line);

     if (errCheck == 0)
     {
       exit(0);
     }
     /*
       Extract each element in the file and store it
      each attribute of transaction.

     */
     t = malloc(sizeof(trnx));
     tokens = malloc(strlen(line));
     amt = malloc(strlen(line));
     strcpy(tokens,line);

     op = strtok(tokens,"\t");
     timeval = strtok(NULL,"\t");
     amt = strtok(NULL,"\t");
     description = strtok(NULL,"\t");
     /*
     Error Check for each of the tokens in the line
     */
     /*
        Operator
     */
     errCheck = 1;
     errCheck = errCheckOp(t,op);
     if (errCheck == 0)
     {
       fputs("Operator is invalid.Must be +/-\n",stderr);
       exit(0);
     }
     /*
        Time
     */
     errCheck = 1;
     errCheck = errCheckTime(&list,t,timeval);
     if (errCheck == 0)
     {
       fputs("Timestamp is invalid.\n",stderr);
       exit(0);
     }
     /*
        Amount
     */
     errCheck = 1;
     errCheck = errCheckAmount(t,amt);
     if (errCheck == 0)
     {
       fputs("Amount is invalid.\n",stderr);
       exit(0);
     }
     /*
       Description
     */
     errCheck = errCheckDesc(t,description);
     if (errCheck == 0)
     {
       exit(0);
     }
     /*
      Create node in the list
     */

     (void)My402ListAppend(&list,(void *)t);
     /*
       Get next element in the list
     */

     //free(tokens);
     //free(amt);
     fgets(line,BUFFER,fp);

   }
   fclose(fp);
   //PrintList(&list);
   BubbleSortList(&list,list.num_members);
   //PrintList(&list);
   DisplayOutput(&list);

}
Пример #25
0
void deterministic_packet_procedure(struct command_line_args *object)
{

	struct packet *p,*p2;
	int i = 0;
	double time, precise_inter_arrival_time, precise_service_time;
	int inter_arrival_time = 0, service_time = 0;
	struct timespec tim;
	struct timeval prev_packet_arrival_time, now, delta;
	long time_diff_in_nsec,delta_time;
	My402ListElem *elem = NULL;

	precise_inter_arrival_time = ((double)1/object->packet_rate);
	inter_arrival_time = (int)(precise_inter_arrival_time);
	if(inter_arrival_time > 10)
	{	
		precise_inter_arrival_time = 10;inter_arrival_time = 10;
	}
	time_diff_in_nsec = (long)((precise_inter_arrival_time - inter_arrival_time)*1000000000L);
	
	
	precise_service_time = ((double)1/object->serving_rate);
	service_time = (int)(precise_service_time);	
	
	if(service_time > 10)
	{	
		precise_service_time = 10;service_time = 10;
	}
	prev_packet_arrival_time.tv_sec = GlobalStartTime.tv_sec;
	prev_packet_arrival_time.tv_usec = GlobalStartTime.tv_usec;

	while(i < object->no_of_packets)
	{
		if((packet_count == object->no_of_packets) && (q1_temp_count == (packet_count-discarded_packets)) && My402ListEmpty(&Q1PacketList))
		{
			pthread_cancel(token_thread);
		}
		gettimeofday(&delta,NULL);
		delta_time = TIME_IN_USEC(delta) - TIME_IN_USEC(prev_packet_arrival_time);
		tim.tv_sec = inter_arrival_time - (delta_time/1000000);
		tim.tv_nsec = (time_diff_in_nsec - (delta_time*1000)) <= 0 ? time_diff_in_nsec : ((time_diff_in_nsec - (delta_time*1000)));
		nanosleep(&tim,NULL);

		packet_count++;
		p = create_packet((precise_inter_arrival_time*1000),(precise_service_time*1000),object->token_per_packet);
		gettimeofday(&(p->Arrival_timestamp), NULL);
		p->precise_packet_inter_arrival = ((TIME_IN_USEC(p->Arrival_timestamp) - TIME_IN_USEC(prev_packet_arrival_time)))/1000;
		time = (TIME_IN_USEC(p->Arrival_timestamp) - TIME_IN_USEC(GlobalStartTime))/1000;

		sum_packet_inter_arrival += p->precise_packet_inter_arrival;
		prev_packet_arrival_time = p->Arrival_timestamp;
		pthread_mutex_lock(&token_bucket);
		if(p->token_per_packet > object->bucket_depth)
		{
			gettimeofday(&now, NULL);
			p->time_in_system = (TIME_IN_USEC(now) - TIME_IN_USEC(p->Arrival_timestamp))/1000;

			LOG(stdout, "%012.3fms: packet p%d arrives, needs %d token%c, dropped\n",time, p->packet_id,p->token_per_packet,(p->token_per_packet > 1?'s':' '));
			free(p);
			discarded_packets++;
			pthread_mutex_unlock(&token_bucket);
			i++;
			continue;
		}
		LOG(stdout, "%012.3fms: p%d arrives, needs %d token%c, inter-arrival time = %.3fms\n",time,p->packet_id, p->token_per_packet,(p->token_per_packet > 1? 's':' ') ,p->precise_packet_inter_arrival);
		My402ListAppend(&Q1PacketList, p);
		gettimeofday(&(p->Q1timestamp), NULL);
		time = (TIME_IN_USEC(p->Q1timestamp) - TIME_IN_USEC(GlobalStartTime))/1000;
		LOG(stdout, "%012.3fms: p%d enters Q1\n",time,p->packet_id);
		elem = My402ListFirst(&Q1PacketList);
		p2 = (struct packet *)elem->obj;
		if(p2->token_per_packet <= tokens_in_bucket)
		{
			tokens_in_bucket -= p2->token_per_packet;
			move_packet_q1_to_q2(object,elem, p2);
		} 	
		
		pthread_mutex_unlock(&token_bucket);
		if((packet_count == object->no_of_packets) && (q1_temp_count == (packet_count-discarded_packets)) && My402ListEmpty(&Q1PacketList))
		{
			pthread_cancel(token_thread);
		}

		i++;
	}


	if((packet_count == object->no_of_packets) &&(q1_temp_count == (packet_count-discarded_packets)) && My402ListEmpty(&Q1PacketList))
	{
			pthread_cancel(token_thread);
	}

	if((packet_count == object->no_of_packets) &&(completed_packets == (packet_count - discarded_packets)) && My402ListEmpty(&Q2PacketList))
	{
		EndServerThread = 1;
		pthread_cond_signal(&is_q2_empty);
	}
}
Пример #26
0
void AddNewNode(char *buf, My402List *List){
    num_line++;
    My402ListElemObj *NewObj;
    NewObj = (My402ListElemObj*)malloc(sizeof(My402ListElemObj));
   /*parse & judge the context of buf*/
   //parsing text input
   char *start_ptr=buf;
   //char *ptr_addr[4];
   char *tab_ptr = strchr(start_ptr, '\t');
   //int countT=0;
   //ptr_addr[countT] = buf;
   char *toomanyfield;

   if(tab_ptr!=NULL)
   {
        *tab_ptr++= '\0';
        //countT++;
        //if(countT>3)
        //    ExitAll("format of this line is incorrect",0);//exit
        //ptr_addr[countT] = tab_ptr;
        NewObj->TSign = (char *)malloc(sizeof(char)*2);
        strncpy(NewObj->TSign,start_ptr,1);

        if(*(NewObj->TSign) !='-' && *(NewObj->TSign) !='+')
            ExitAll(" cannot caculate with wrong symbol ",num_line);

        //printf("%s",NewObj->TSign);

        start_ptr=tab_ptr;//can delete
        tab_ptr = strchr(start_ptr, '\t');
    }
    else
    {
        ExitAll(" the format is wrong ",num_line);
    }
    if(tab_ptr!=NULL)
    {
        *tab_ptr++= '\0';
        //countT++;
        //if(countT>3)
        //    ExitAll("format of this line is incorrect",0);//exit
        //ptr_addr[countT] = tab_ptr;
        NewObj->TTime = atol(start_ptr);

        if(NewObj->TTime > time(NULL))
            ExitAll(" time is over the current time ",num_line);
        //printf("%d\n",NewObj->TTime);

        start_ptr=tab_ptr;//can delete
        tab_ptr = strchr(start_ptr, '\t');
    }
    else
    {
        ExitAll(" the format is wrong ",num_line);
    }
    if(tab_ptr!=NULL)
    {
        *tab_ptr++= '\0';
        //countT++;
        //if(countT>3)
        //    ExitAll("format of this line is incorrect",0);//exit
        //ptr_addr[countT] = tab_ptr;
        char *toomanydecimal = strchr(start_ptr,'.');
        if(strlen(toomanydecimal)>3)
        {
            ExitAll(" too many decimal ",num_line);
        }
        NewObj->TAm =(char *)malloc(sizeof(char)*11);
        strncpy(NewObj->TAm,start_ptr,10);

        //printf("%s\n",NewObj->TAm);

        start_ptr=tab_ptr;//can delete
        tab_ptr = strchr(start_ptr, '\n');
        toomanyfield=strchr(start_ptr, '\t');
    }
    else
    {
        ExitAll(" the format is wrong ",num_line);
    }
    if(toomanyfield!=NULL)
    {
        ExitAll(" too many field ",num_line);
    }
    if(tab_ptr!=NULL)
    {
        *tab_ptr= '\0';
        while(*start_ptr == ' ')
        {
            start_ptr++;
        }
        //countT++;
        //if(countT>3)
        //    ExitAll("format of this line is incorrect",0);//exit
        //ptr_addr[countT] = tab_ptr;
        NewObj->TDesc = (char *)malloc(sizeof(char)*25);
        strncpy(NewObj->TDesc,start_ptr,24);

        //printf("%s\n", NewObj->TDesc);

        //start_ptr=tab_ptr;//can delete
        //tab_ptr = strchr(start_ptr, '\t');
    }
    else
    {
        ExitAll(" the format is wrong ",num_line);
    }

    /*check every part*/

   /*add new obj*/
   //malloc & initial new node
   //NewObj = (My402ListElemObj*)malloc(sizeof(My402ListElemObj));
   //strcpy(NewObj->TSign,ptr_addr[0]);
   //NewObj->TTime = atol(ptr_addr[1]);
   //strcpy(NewObj->TAm,ptr_addr[2]);
   //strcpy(NewObj->TDesc,ptr_addr[3]);
   //add new node to list
   int ToF;
   ToF = My402ListAppend(List, NewObj); //void* with My402ListElemObj*
   if(ToF == 0)
    ExitAll("A node cannot be added when initial the list",0);//exit~
}
Пример #27
0
int pushToken()
{
    My402ListAppend(&tokList, (void *)0);
    return 1;
}
Пример #28
0
void *tokenThread(void *id)
{
	long sleep_time;
	int queue2_empty;
	int token_drop=0;
	Packet *pkt;
	My402ListElem *elem;
	while(1) {

		if(token_die==1) {
			token_drop_prob = (double)token_drop/tokencount;
			pthread_exit(NULL);
		}

		ttend=getinstanttime();
		sleep_time = tokenarrival - (ttend-ttstart);
		usleep(sleep_time);	
		ttstart = getinstanttime();
		pthread_mutex_lock(&my_mutex);
		if(token_bucket<B) {
			token_bucket++;
			tokencount++;
			PrintStat(getinstanttime());
			fprintf(stdout,"token t%d arrives, token bucket now has %d tokens\n",tokencount,token_bucket);
		}
		else {
			PrintStat(getinstanttime());
			tokencount++;
			token_drop++;
			fprintf(stdout,"token t%d arrives, token bucket full, token dropped!!\n",tokencount);
		}
		
		if(!My402ListEmpty(&queue1)) {
			elem = My402ListFirst(&queue1);
			pkt = (Packet *)elem->obj;
			if(token_bucket >= pkt->num_tokens) {
				token_bucket-=pkt->num_tokens;
				My402ListUnlink(&queue1,elem);
				pkt->q1_exit = getinstanttime();
				PrintStat(getinstanttime());
				fprintf(stdout, "p%d leaves Q1, time in Q1 = %.3fms, token bucket now has %d tokens\n", 
					pkt->pkt_id, (double)(pkt->q1_exit - pkt->q1_enter)/1000, token_bucket);
				avg_pkt_q1 += (pkt->q1_exit - pkt->q1_enter);
				pkts_left_q1++;
				queue2_empty = My402ListEmpty(&queue2);
				My402ListAppend(&queue2,pkt);
				pkt->q2_enter = getinstanttime();
				PrintStat(getinstanttime());
				fprintf(stdout,"p%d enters Q2\n", pkt->pkt_id);

				if(queue2_empty==1)
					pthread_cond_signal(&queue2_cond);
			}
		}
		pthread_mutex_unlock(&my_mutex);
		if(pkts_left_q1 == pkts_to_arrive) {
			token_drop_prob = (double)token_drop/tokencount;
			pthread_exit(NULL);	
		}
	}
}
Пример #29
0
void *arrivalThread(void *id)
{
	My402ListElem *elem;
	Packet *pkt;
	int i;
	long pkt_sleep, pkt_service;
	int pkt_token;
	long sleep_time;
	long prev_pkt_time=0, instant_time;
	long avg_ia=0;


	for (i=0;i<num_packets;i++) {


		getStatistics(&pkt_sleep,&pkt_service,&pkt_token,i);		
		if(pkt_sleep > 10000000)
			pkt_sleep = 10000000;
		if(pkt_service > 1000000)
			pkt_service = 10000000;
				
		taend=getinstanttime();
		sleep_time = pkt_sleep - (taend-tastart);
		usleep(sleep_time);
		
		// Creating the Packet
		
		pkt = (Packet *)malloc(sizeof(struct tagPacket));
		pkt->pkt_id = i;
		pkt->num_tokens = pkt_token;
		pkt->service_time = pkt_service;

		pkt->sys_enter = tastart = getinstanttime();
		if(pkt->num_tokens > B) {
			// Drop the packet
			pkts_to_arrive--;
			PrintStat(getinstanttime());
			fprintf(stdout, "p%d arrives, Invalid token requirement, p%d Dropped!!\n", 
				pkt->pkt_id, pkt->pkt_id);
			continue;
		}
		else {
			instant_time = getinstanttime();
			if(prev_pkt_time==0) {
				prev_pkt_time = pkt->inter_arrival_time = (instant_time - temulation_start);
				prev_pkt_time = instant_time;
			}
			else {
				pkt->inter_arrival_time = instant_time - prev_pkt_time;
				prev_pkt_time = instant_time;
			}
			PrintStat(instant_time);
			avg_ia += pkt->inter_arrival_time;
			fprintf(stdout, "p%d arrives, needs %d tokens, inter-arrival time = %.3fms\n",
				pkt->pkt_id,pkt->num_tokens,(double)(pkt->inter_arrival_time)/1000);
		}

		pthread_mutex_lock(&my_mutex);
		if(My402ListEmpty(&queue1)){
			My402ListAppend(&queue1,pkt);
			pkt->q1_enter = getinstanttime();
			PrintStat(getinstanttime());
			fprintf(stdout,"p%d enters Q1\n", pkt->pkt_id);
			if(!My402ListEmpty(&queue2)) {
				pthread_cond_signal(&queue2_cond);
			}
			else {
				if(token_bucket >= pkt->num_tokens) {
					elem = My402ListFirst(&queue1);
					pkt = (Packet *)elem->obj;					

					My402ListUnlink(&queue1,elem);
					pkt->q1_exit = getinstanttime();
					token_bucket-=pkt->num_tokens;
					PrintStat(getinstanttime());
					fprintf(stdout, "p%d leaves Q1, time in Q1 = %.3fms, token bucket now has %d tokens\n", 
						pkt->pkt_id, (double)(pkt->q1_exit - pkt->q1_enter)/1000, token_bucket);
					avg_pkt_q1 += (pkt->q1_exit - pkt->q1_enter);
					pkts_left_q1++;
					My402ListAppend(&queue2,pkt);
					pkt->q1_enter = 0;
					pkt->q1_exit = 0;
					pkt->q2_enter = getinstanttime();
					PrintStat(getinstanttime());
					fprintf(stdout,"p%d enters Q2\n", pkt->pkt_id);
					pthread_cond_signal(&queue2_cond);
				}
			}
		}
		else {
			My402ListAppend(&queue1,pkt);
			pkt->q1_enter = getinstanttime();
			PrintStat(getinstanttime());
			fprintf(stdout,"p%d enters Q1\n", pkt->pkt_id);
		}
		pthread_mutex_unlock(&my_mutex);
	}
	pthread_mutex_lock(&my_mutex);
	pthread_cond_signal(&queue2_cond); // This can also be a false signal just to wake up server, if
	pthread_mutex_unlock(&my_mutex);   // say last packet is dropped and there is no pkt to be queued to q2.
	if(i==-1) {
		avg_inter_arrival = 0;
		pkt_drop_prob = 0;
	}
	else {
		avg_inter_arrival = (double)((double)avg_ia/(double)((i+1)*1000000));
		pkt_drop_prob = (double)(num_packets - pkts_to_arrive)/(i+1);
	}
	pthread_exit(NULL);
}
Пример #30
0
int main(int argc, char *argv[])
{
		My402List list;
   // My402ListElem *elem=NULL;

    memset(&list, 0, sizeof(My402List));
    (void)My402ListInit(&list);
	
	//Transact t;
	
	
			FILE *fptr;
			//char address[100]="test.tfile";
		char buf[200];
	//printf("ARGC: %d\n",argc);
	if(argc<2)//if sort is missing
	{
		printf("Malformed command\n");
		exit(0);
	}
	if((strcmp(argv[1],"sort")))//if second argument is not 'sort'
	{
		printf("Malformed command\n");
		exit(0);
	}
	if(argc==2)
	{
			fptr=stdin;			
	}
	if(argc==3)
	{		
		if(!strstr(argv[2],".tfile"))
		{
			printf("Could not open file: %s\n",argv[2]);
			printf("Input file either a directory or not in correct format\n");
			exit(0);
		}
		
		fptr=fopen(argv[2], "rt"); 		
	}
    if (fptr==NULL) 
    { //perror("Error:");
       // printf("%s",argv[2]);
        printf("Could not open file: %s!\n",argv[2]); // error in opening file
		printf("%s\n", strerror(errno));
		exit(0);
		//perror("Error:");
        // getch();
        return 1; 
    }
    else
    {
	
		while(fgets(buf, sizeof(buf), fptr) != NULL)
		{
			// if (fgets(buf, sizeof(buf), fptr) == NULL)
		// {
		  // /* end of file */
		  // break;
		// } 
	//else 
	//	{
			//printf("%s",argv[3]);
			//printf("==%s==",buf);
			//printf("COMING TILL HERE!!!\n");
			if(strlen(buf)>1024)
			{
				printf("Invalid input, line is too long\n");
				exit(0);
			}
			long timeint;
			char timec[30];//change size 
			char op;
			//float amt;
			double a=0.0;
			char desc[40];//change size!!!
			//else 
			{
				
				Transact *t;
				t=malloc(sizeof(struct data));
				//printf("BUF: %s\n",buf);
				int i;
				
				char *start_ptr = buf;
				if(!strchr(start_ptr,'\t'))
				{
					printf("Invalid input, not enough info\n");
					exit(0);
				}
				//char *nline_ptr;
				if(strchr(start_ptr,'\r'))
				{
				char *nline_ptr = strchr(start_ptr,'\r');
				*nline_ptr++='\0';
				}
				if(strchr(start_ptr,'\n'))
				{
				char *nline_ptr = strchr(start_ptr,'\n');
				*nline_ptr++='\0';
				}
				char *tab_ptr = strchr(start_ptr, '\t');
				if (tab_ptr != NULL) 
				{
				  *tab_ptr++ = '\0';
				 // printf("%s\t",start_ptr);
				  op=start_ptr[0];
						//printf("OPERATOR= %c\n",op);
						t->op=op;
						if(((op!='+')&&(op!='-')))
						{
							printf("Invalid input with Operator: %c\n",t->op);
							exit(1);
						}
					//	printf("%c\t",t->op);
				}
				for(i=0;i<3;i++)
				{
					start_ptr = tab_ptr;
					// if(!strchr(start_ptr,'\t'))
					// {
						// printf("Invalid input, not enough info2\n");
						// //exit(0);
					// }
						tab_ptr = strchr(start_ptr, '\t');
					//nline_ptr= strchr(start_ptr, '\n');
					
					if ((tab_ptr != NULL)) 
					{
					  *tab_ptr++ = '\0';
					  
					}
					if(i==0)
					{
												
						if(strlen(start_ptr)>=11)
						{
							printf("Invalid input in timestamp: %s\n",start_ptr);
							exit(0);
						}
						if(!((atoi(start_ptr)>0)&&(atoi(start_ptr)<time(NULL))))
						{
							printf("Invalid input in timestamp\n");
							exit(0);
						}
					
						 timeint=atol(start_ptr);
						t->ltime=timeint;
						//printf("--TIME: %lu\t",timeint);
						strcpy(timec,ctime(&timeint));//time is stored in array time
						
					}
					else if(i==1)
					{
						//if(start_ptr[strlen(start_ptr)-3]
					  if(strlen(start_ptr)<4)//min should have one digit before decimal, 2 after and decimal itself
					  {
						printf("Invalid input, not enough digits or decimal\n");
						exit(0);
					  }
					 // if((start_ptr[strlen(start_ptr)-3]!='.')&&(start_ptr[0]=='.'))
					// printf("%c",start_ptr[strlen(start_ptr)-3]);
					  if((start_ptr[strlen(start_ptr)-3]!='.'))
					  {
						printf("Invalid input, does not contain decimal or enough digits after decimal: %s\n",start_ptr);
						exit(0);
					   }
					  if(start_ptr[0]=='.')
					  {
						printf("Invalid input, no digit before decimal\n");
						exit(0);
					  }
						a=atof(start_ptr);
						
						if((a>10000000)||(a<0))
						{
							printf("Invalid input with Amount\n");
							exit(1);
						}
						t->amt=a*100;
						
						
	
						// sprintf(chk, "%0.2f",a);
						// printf("STRING: %s\n",chk);
						// printf("Invalid input, does not contain decimal: %c\n",chk[strlen(chk)-2]);
						// // if(chk[strlen(chk)-3]!='.')
							// // printf("Invalid input, does not contain decimal: %c\n",chk[strlen(chk)-2]);
						
						//printf("AMOUNT: %f--\t",a);
						//printf("%f\t",a);
						//printf("%d\t",t->amt);
					}
					else if(i==2)
					{
						while(isspace(*start_ptr)) 
							start_ptr++;

					    if(*start_ptr == 0)  // All spaces?
						{
							printf("Invalid input..No description\n");
							exit(0);
						}
						if(strlen(start_ptr)>24)
							strncpy(desc,start_ptr,23);
						else
							strcpy(desc,start_ptr);
						
						strcpy(t->desc,desc);
						//t->desc=desc;
						//printf("Description%s",start_ptr);
						//printf("%s\n",t->desc);
					}
				//	printf("%s\t",start_ptr);
				}
				//printf("\n");
				if(checkTime(&list,t->ltime))//1 returned if same exists
				{
					printf("Two same timestamps detected\n");
					exit(0);
				}
				//printf("CTIME:%s",ctime(&time));	
				//printf("Appending\n");
				My402ListAppend(&list,t);
			
			}
		 //}
	  }//while loop
	}
	BubbleSortForwardList(&list,list.num_members);
	PrintTestList(&list,list.num_members);
  
 
    return(0);
}