示例#1
0
文件: core.v1.c 项目: pthalamy/bench
void tuple_do_handle(tuple_type type,	tuple_t tuple, int isNew, Register *reg)
{
  if(TYPE_IS_PROVED(type)) {
    PROVED[type] += (meld_int)isNew;
    tuple_t _proved = tuple_build_proved(type, PROVED[type]);
#ifdef DEBUG_PROVED_TUPLES
    printf("New proved for tuple %s: %d\n", tuple_names[type], PROVED[type]);
#endif
    PUSH_NEW_TUPLE(_proved);
  } else if(type == TYPE_PROVED) {
    tuple_process(tuple, TYPE_START(type), isNew, reg);
    FREE_TUPLE(tuple);
    return;
  } else if(type == TYPE_TERMINATE) {
    FREE_TUPLE(tuple);
    TERMINATE_CURRENT();
    return;
  }
  
  if(!TYPE_IS_AGG(type) && TYPE_IS_PERSISTENT(type)) {
    persistent_set *persistents = &PERSISTENT[type];
    int i;
    int size = TYPE_SIZE(type);
    
    if(isNew < 0) {
      fprintf(stderr, "meld: persistent types can't be deleted\n");
      exit(EXIT_FAILURE);
    }
    
    for(i = 0; i < persistents->total; ++i) {
      void *stored_tuple = persistents->array + i * size;
      
      if(memcmp(stored_tuple, tuple, size) == 0) {
        FREE_TUPLE(tuple);
        return;
      }
    }
    
    /* new tuple */
    if(persistents->total == persistents->current) {
      if(persistents->total == 0)
        persistents->total = PERSISTENT_INITIAL;
      else
        persistents->total *= 2;
        
      persistents->array = realloc(persistents->array, size * persistents->total);
    }
    
    memcpy(persistents->array + persistents->current * size, tuple, size);
    ++persistents->current;
    
    tuple_process(tuple, TYPE_START(type), isNew, reg);
    
    return;
  }
  
  if (!TYPE_IS_AGG(type) || TYPE_IS_LINEAR(type))
    {
      tuple_queue *queue = &TUPLES[type];
      tuple_entry** current;
      tuple_entry* cur;
		
      for (current = &queue->head;
	   *current != NULL;
	   current = &(*current)->next)
	{
	  cur = *current;

	  if (memcmp(cur->tuple,
		     tuple,
		     TYPE_SIZE(type)) == 0)
	    {
	      cur->records.count += isNew;

	      if (cur->records.count <= 0) {
		/* only process if it isn't linear */
		if (!TYPE_IS_LINEAR(type)) {
		  tuple_process(tuple, TYPE_START(TUPLE_TYPE(tuple)), -1, reg);
		  FREE_TUPLE(queue_dequeue_pos(queue, current));
		} else {
		  if(DELTA_WITH(type)) {
		    if(OLDTUPLES[type])
		      FREE_TUPLE(OLDTUPLES[type]);
                
		    OLDTUPLES[type] = queue_dequeue_pos(queue, current);
		  } else
		    FREE_TUPLE(queue_dequeue_pos(queue, current));
		}
	      }

	      FREE_TUPLE(tuple);

	      return;
	    }
	}

      // if deleting, return
      if (isNew <= 0) {
	FREE_TUPLE(tuple);
	return;
      }

      queue_enqueue(queue, tuple, (record_type) isNew);

      if(TYPE_IS_LINEAR(type) && DELTA_WITH(type))
	process_deltas(tuple, type, reg);

      tuple_process(tuple, TYPE_START(TUPLE_TYPE(tuple)), isNew, reg);

      return;
    }

  unsigned char type_aggregate = TYPE_AGGREGATE(type);
  unsigned char field_aggregate = AGG_FIELD(type_aggregate);

  tuple_entry **current;
  tuple_entry *cur;
  tuple_queue *queue = &(TUPLES[type]);
	
  for (current = &queue->head;
       (*current) != NULL;
       current = &(*current)->next)
    {
      cur = *current;
    
      size_t sizeBegin = TYPE_FIELD_SIZE + TYPE_ARG_OFFSET(type, field_aggregate);
      char *start = (char*)(cur->tuple);

      if(memcmp(start, tuple, sizeBegin))
	continue;

      /*
	size_t sizeOffset = sizeBegin + TYPE_ARG_SIZE(type, field_aggregate);
	size_t sizeEnd = TYPE_SIZE(type) - sizeOffset;

	if (memcmp(start + sizeOffset, (char*)tuple + sizeOffset, sizeEnd))
	continue;*/

      tuple_queue *agg_queue = cur->records.agg_queue;

      /* AGG_FIRST aggregate optimization */
      if(AGG_AGG(type_aggregate) == AGG_FIRST
	 && isNew > 0
	 && !queue_is_empty(agg_queue))
	{
	  FREE_TUPLE(tuple);
	  return;
	}

      tuple_entry** current2;
      tuple_entry* cur2;
		
      for (current2 = &agg_queue->head;
	   *current2 != NULL;
	   current2 = &(*current2)->next)
	{
	  cur2 = *current2;

	  if (memcmp(cur2->tuple, tuple, TYPE_SIZE(type)) == 0)
	    {
	      cur2->records.count += isNew;

	      if (cur2->records.count <= 0) {
		// remove it
		FREE_TUPLE(queue_dequeue_pos(agg_queue, current2));

		if (queue_is_empty(agg_queue)) {
		  /* aggregate is removed */
		  void *aggTuple = queue_dequeue_pos(queue, current);
						
		  /* delete queue */
		  free(agg_queue);

		  tuple_process(aggTuple, TYPE_START(TUPLE_TYPE(aggTuple)), -1, reg);
		  aggregate_free(aggTuple, field_aggregate, AGG_AGG(type_aggregate));
		  FREE_TUPLE(aggTuple);
		} else
		  aggregate_recalc(cur, reg, false);
	      } else
		aggregate_recalc(cur, reg, false);

	      FREE_TUPLE(tuple);
	      return;
	    }
	}

      // if deleting, return
      if (isNew <= 0) {
	FREE_TUPLE(tuple);
	return;
      }

      queue_enqueue(agg_queue, tuple, (record_type) isNew);
      aggregate_recalc(cur, reg, false);
		
      return;
    }

  // if deleting, return
  if (isNew <= 0) {
    FREE_TUPLE(tuple);
    return;
  }

  // So now we know we have a new tuple
  tuple_t tuple_cpy = ALLOC_TUPLE(TYPE_SIZE(type));
  memcpy(tuple_cpy, tuple, TYPE_SIZE(type));

  /* create aggregate queue */
  tuple_queue *agg_queue = malloc(sizeof(tuple_queue));
  
  queue_init(agg_queue);
  
  queue_enqueue(agg_queue, tuple, (record_type) isNew);
  tuple_entry *entry =
    queue_enqueue(&TUPLES[type], tuple_cpy, (record_type)agg_queue);

  aggregate_recalc(entry, reg, true);
  tuple_process(tuple, TYPE_START(type), isNew, reg);
}
示例#2
0
void sched_schedule(fthread_t thr) {
  queue_enqueue(&sched_runq, thr);
}
void test_queue_students()
{
	queue struct_queue;
	queue_new(&struct_queue, sizeof(students_group), students_group_free);


	// ENQUEUE
	{
		students_group group_1;
		group_1.elem = 4;

		char* names_1[] = {"Al", "Bob", "Carl", "John"};
		const int notas_1[] = {3, 4, 5, 3};

		group_1.names = malloc(group_1.elem * sizeof(char*));
		group_1.cal = malloc(group_1.elem * sizeof(int));

		for (int j = 0; j < group_1.elem; ++j) {
			group_1.names[j] = malloc((strlen(names_1[j]) + 1)*sizeof(char));
			strcpy(group_1.names[j], names_1[j]);
			group_1.cal[j] = notas_1[j];
		}
		queue_enqueue(&struct_queue, &group_1);
	}

	// ENQUEUE
	{
		students_group group_2;
		group_2.elem = 6;
		const char* names_2[] = {"Lou", "David", "Steven", "Logan", "Popi", "Juno"};
		const int notas_2[] = {1, 2, 3, 2, 0, 2};

		group_2.names = malloc(group_2.elem * sizeof(char*));
		group_2.cal = malloc(group_2.elem * sizeof(int));

		for (int j = 0; j < group_2.elem; ++j) {
			group_2.names[j] = malloc((strlen(names_2[j]) + 1)*sizeof(char));
			strcpy(group_2.names[j], names_2[j]);
			group_2.cal[j] = notas_2[j];
		}

		queue_enqueue(&struct_queue, &group_2);
	}

	// DEQUEUE
	students_group aux;
	queue_dequeue(&struct_queue, &aux);
	printf("First element\n");
	print_students(&aux, NULL);
	students_group_free(&aux);

	// DEQUEUE
	queue_dequeue(&struct_queue, &aux);
	printf("Second element\n");
	print_students(&aux, NULL);
	students_group_free(&aux);

	// ENQUEUE
	{
		students_group group_2;
		group_2.elem = 6;
		const char* names_2[] = {"Lou", "David", "Steven", "Logan", "Popi", "Juno"};
		const int notas_2[] = {1, 2, 3, 2, 0, 2};

		group_2.names = malloc(group_2.elem * sizeof(char*));
		group_2.cal = malloc(group_2.elem * sizeof(int));

		for (int j = 0; j < group_2.elem; ++j) {
			group_2.names[j] = malloc((strlen(names_2[j]) + 1)*sizeof(char));
			strcpy(group_2.names[j], names_2[j]);
			group_2.cal[j] = notas_2[j];
		}

		queue_enqueue(&struct_queue, &group_2);
	}

	{
		students_group group_2;
		group_2.elem = 6;
		const char* names_2[] = {"zzzzzz", "xxxxxx", "yyyyyy", "wwwwww", "uuuuuuu", "pppppp"};
		const int notas_2[] = {1, 2, 3, 2, 0, 2};

		group_2.names = malloc(group_2.elem * sizeof(char*));
		group_2.cal = malloc(group_2.elem * sizeof(int));

		for (int j = 0; j < group_2.elem; ++j) {
			group_2.names[j] = malloc((strlen(names_2[j]) + 1)*sizeof(char));
			strcpy(group_2.names[j], names_2[j]);
			group_2.cal[j] = notas_2[j];
		}

		queue_enqueue(&struct_queue, &group_2);
	}

	// DEQUEUE
	queue_dequeue(&struct_queue, &aux);
	printf("Third element\n");
	print_students(&aux, NULL);
	students_group_free(&aux);

	// ENQUEUE
	{
		students_group group_2;
		group_2.elem = 6;
		const char* names_2[] = {"Lou", "David", "Steven", "Logan", "Popi", "Juno"};
		const int notas_2[] = {1, 2, 3, 2, 0, 2};

		group_2.names = malloc(group_2.elem * sizeof(char*));
		group_2.cal = malloc(group_2.elem * sizeof(int));

		for (int j = 0; j < group_2.elem; ++j) {
			group_2.names[j] = malloc((strlen(names_2[j]) + 1)*sizeof(char));
			strcpy(group_2.names[j], names_2[j]);
			group_2.cal[j] = notas_2[j];
		}

		queue_enqueue(&struct_queue, &group_2);
	}

	// ENQUEUE
	{
		students_group group_2;
		group_2.elem = 6;
		const char* names_2[] = {"AAA", "BBB", "CCC", "DDD", "EEE", "FFF"};
		const int notas_2[] = {1, 2, 3, 2, 0, 2};

		group_2.names = malloc(group_2.elem * sizeof(char*));
		group_2.cal = malloc(group_2.elem * sizeof(int));

		for (int j = 0; j < group_2.elem; ++j) {
			group_2.names[j] = malloc((strlen(names_2[j]) + 1)*sizeof(char));
			strcpy(group_2.names[j], names_2[j]);
			group_2.cal[j] = notas_2[j];
		}

		queue_enqueue(&struct_queue, &group_2);
	}

	for (int i = 0; i < 3; ++i) {
		students_group aux;
		queue_dequeue(&struct_queue, &aux);
		printf("Inside 'for' element\n");
		print_students(&aux, NULL);
		students_group_free(&aux);
	}

	queue_dispose(&struct_queue);
}
示例#4
0
void initialize_sequence_queue(SearchTree tree) {
    sequence_queue = queue_create();
    queue_enqueue(sequence_queue, tree->data);
}
示例#5
0
文件: libjl777.c 项目: apex944/btcd
void SuperNET_idler(uv_idle_t *handle)
{
    static int counter;
    static double lastattempt,lastclock;
    double millis;
    void *up;
    struct udp_queuecmd *qp;
    struct write_req_t *wr,*firstwr = 0;
    int32_t flag;
    char *jsonstr,*retstr,**ptrs;
    if ( Finished_init == 0 )
        return;
    millis = milliseconds();//((double)uv_hrtime() / 1000000);
    if ( millis > (lastattempt + APISLEEP) )
    {
        lastattempt = millis;
#ifdef TIMESCRAMBLE
        while ( (wr= queue_dequeue(&sendQ)) != 0 )
        {
            if ( wr == firstwr )
            {
                //queue_enqueue(&sendQ,wr);
                process_sendQ_item(wr);
                if ( Debuglevel > 2 )
                    printf("SuperNET_idler: reached firstwr.%p\n",firstwr);
                break;
            }
            if ( wr->queuetime == 0 || wr->queuetime > lastattempt )
            {
                process_sendQ_item(wr);
                // free(wr); libuv does this
                break;
            }
            if ( firstwr == 0 )
                firstwr = wr;
            queue_enqueue(&sendQ,wr);
        }
        if ( Debuglevel > 2 && queue_size(&sendQ) != 0 )
            printf("sendQ size.%d\n",queue_size(&sendQ));
#else
#endif
        flag = 1;
        while ( flag != 0 )
        {
            flag = 0;
            if ( (qp= queue_dequeue(&udp_JSON)) != 0 )
            {
                //printf("process qp argjson.%p\n",qp->argjson);
                char previpaddr[64];
                expand_ipbits(previpaddr,qp->previpbits);
                jsonstr = SuperNET_json_commands(Global_mp,previpaddr,qp->argjson,qp->tokenized_np->H.U.NXTaddr,qp->valid,qp->decoded);
                //printf("free qp (%s) argjson.%p\n",jsonstr,qp->argjson);
                if ( jsonstr != 0 )
                    free(jsonstr);
                free(qp->decoded);
                free_json(qp->argjson);
                free(qp);
                flag++;
            }
            else if ( (ptrs= queue_dequeue(&JSON_Q)) != 0 )
            {
                char *call_SuperNET_JSON(char *JSONstr);
                jsonstr = ptrs[0];
                if ( Debuglevel > 2 )
                    printf("dequeue JSON_Q.(%s)\n",jsonstr);
                if ( (retstr= call_SuperNET_JSON(jsonstr)) == 0 )
                    retstr = clonestr("{\"result\":null}");
                ptrs[1] = retstr;
                if ( ptrs[2] != 0 )
                    queue_GUIpoll(ptrs);
                flag++;
            }
        }
        if ( process_storageQ() != 0 )
        {
            //printf("processed storage\n");
        }
    }
#ifndef TIMESCRAMBLE
    while ( (wr= queue_dequeue(&sendQ)) != 0 )
    {
        //printf("sendQ size.%d\n",queue_size(&sendQ));
        process_sendQ_item(wr);
    }
#endif
    while ( (up= queue_dequeue(&UDP_Q)) != 0 )
        process_udpentry(up);
    if ( millis > (lastclock + 1000) )
    {
        poll_pricedbs();
        every_second(counter);
        retstr = findaddress(0,0,0,0,0,0,0,0,0,0);
        if ( retstr != 0 )
        {
            printf("findaddress completed (%s)\n",retstr);
            free(retstr);
        }
        if ( (counter % 60) == 17 )
        {
            every_minute(counter/60);
            update_Allnodes();
            poll_telepods("BTCD");
            poll_telepods("BTC");
        }
        counter++;
        lastclock = millis;
    }
    usleep(APISLEEP * 1000);
}
示例#6
0
void process_queues(queue_t *rest_r, queue_t *ready_r, queue_t *complete_t)
{
	int i = 0;
	while(i < queue_size(rest_r))
	{
		int satify = 1;
		int dependR = 0; 
		rule_t *rule = queue_at(rest_r, i);
		int j;
		
		for (j = 0; j < queue_size(rule->deps); j++)
		{
			char *dep = queue_at(rule->deps, j);

			int complete = 0;
			if (isRule(dep))
			{
				int k;
				for (k = 0; k < queue_size(complete_t); k++)
				{
					char *target = queue_at(complete_t, k);
					if (strcmp(dep, target) == 0)
					{
						dependR = 1;
						complete = 1;
						break;
					}
				}
			}
			else
			{
				if (access(dep, R_OK) == 0)
				{
					complete = 1;		
				}
				else 
				{
					fprintf(stderr,"dependency file does not exist!");
					exit(1);	
				}
			}

			if (!complete)
			{
				satify = 0;	
				break;
			}
			
		}
		
		if (satify)
		{
			if (dependR)
			{
				queue_enqueue(ready_r, rule);	
				queue_remove_at(rest_r, i);
			}
			else 
			{
				if (access(rule->target, R_OK) == -1)
				{
					queue_enqueue(ready_r, rule);	
					queue_remove_at(rest_r, i);
				}
				else 
				{
					struct stat statbuf;
					stat(rule->target, &statbuf);
					time_t rule_time = statbuf.st_mtime; 	
					
					int run = 0;
					int j;
					for (j = 0; j < queue_size(rule->deps); j++)
					{
						char *dep = queue_at(rule->deps, j);
						stat(dep, &statbuf);
						time_t dep_time = statbuf.st_mtime;
						if (dep_time > rule_time)
						{
							run = 1;
							queue_enqueue(ready_r, rule);	
							queue_remove_at(rest_r, i);
							break;
						}
					}
					
					if (!run)
					{
						queue_remove_at(rest_r, i);
						queue_enqueue(complete_t, rule->target);
						
						while(queue_size(rule->deps))
						{
							char *dep = queue_dequeue(rule->deps);
							free(dep);
						}
						while(queue_size(rule->commands))
						{
							char *command = queue_dequeue(rule->commands);
							free(command);
						}
						rule_destroy(rule);
						free(rule);
					}
				}
			}
		}
		else
		{
			i++;	
		}
	}
}
示例#7
0
文件: downloader.c 项目: jucs/musicfs
static void downloader_do_work(void *arg) {
	pthread_detach(pthread_self());
	pthread_mutex_lock(thread_counter_mutex);
	if(threads < 0)
		pthread_exit(NULL);
	else
		threads++;
	pthread_mutex_unlock(thread_counter_mutex);
	
	logging_log("Donwloader", LOGGING_LEVEL_INFO, "Downloader thread started...");
	
	while(1) {
		pthread_mutex_lock(downloader_files_mutex);
		while(!queue_get_length(downloader_requests_queue)) {
			pthread_cond_wait(downloader_requests_cond, downloader_files_mutex);
			pthread_mutex_lock(thread_counter_mutex);
			if(threads < 0) {
				logging_log("Downloader", LOGGING_LEVEL_INFO, "Thread terminating...");
				threads++;
				pthread_cond_broadcast(thread_terminating);
				pthread_mutex_unlock(thread_counter_mutex);
				pthread_mutex_unlock(downloader_files_mutex);
				pthread_exit(NULL);
			}
			pthread_mutex_unlock(thread_counter_mutex);
			logging_log("Donwloader", LOGGING_LEVEL_INFO, "Downloader thread woke up...");
		}

		logging_log("Donwloader", LOGGING_LEVEL_INFO, "Dequeuing job...");
		
		downloader_request_t *current_request = (downloader_request_t*)queue_dequeue(
				downloader_requests_queue);
		pthread_mutex_unlock(downloader_files_mutex);
		
		logging_log("Donwloader", LOGGING_LEVEL_INFO, "current_request=%p...", current_request);
		
		size_t buffer_size = http_get_file_with_callback(current_request->url,
				(char**)&current_request->file->contents,
				&downloader_http_memory_write_begin_callback,
				&downloader_http_memory_write_end_callback, current_request);
		
		pthread_mutex_lock(downloader_files_mutex);
		pthread_mutex_lock(current_request->mutex);
		if(buffer_size > current_request->file->size) {
			logging_log("Downloader", LOGGING_LEVEL_CRITICAL,
					"Did not receive memory write callback for every chunk...");
		}
		current_request->finished = 1;
		if(current_request->file->size)
			current_request->file->contents = realloc(current_request->file->contents,
					current_request->file->size);
		
		downloader_files_size += current_request->file->size;
		if(current_request->reference_count)
			current_request->reference_count--;
		
		pthread_cond_broadcast(current_request->minimum_size_reached);
		pthread_mutex_unlock(current_request->mutex);
		
		queue_enqueue(downloader_files_free_queue, current_request);
		downloader_garbage_collect();
		
		pthread_mutex_unlock(downloader_files_mutex);
		
		logging_log("Donwloader", LOGGING_LEVEL_INFO, "Job finished...");
	}
}
示例#8
0
文件: syard.c 项目: ohnx/leo
/* reverse polish https://en.wikipedia.org/wiki/Shunting-yard_algorithm */
queue *syard_run(const char *in) {
    /* init */
    stack *s, *arity;
    queue *q;
    int len;
    tokenizer_ctx *tkc;
    char *tok, *op, *newstr;
    tokenizer_type tok_last = TOKEN_LBRACKET;
    char comma = ',', mul = '*';
    int *arn;

    s = stack_new();
    arity = stack_new();
    q = queue_new();
    tkc = tokenizer_new();
    newstr = strdup(in);
    newstr[strcspn(newstr, "\r\n")] = 0; /* strip newlines */
    tokenizer_reset(tkc, newstr);

    /* while there are tokens to be read, read a token. */
    while ((tok = tokenizer_next(tkc)) != NULL) {
        switch (tkc->type) {
        /* if the token is a number, then push it to the output queue. */
        case TOKEN_NUMBER:
            /* special case: last token was a rbracket and we have number now */
            if (tok_last == TOKEN_RBRACKET) {
                /* push a * sign with high precendence */
                stack_push(s, (void *)&mul);
            }
            queue_enqueue(q, syard_create_double(tok));
            break;
        /* if the token is an operator, then: */
        case TOKEN_OPERATOR:
            /* special case: last token was left bracket or operator and we have a minus sign now */
            if ((tok_last == TOKEN_LBRACKET || tok_last == TOKEN_OPERATOR) && (*tok == '-')) {
                /* change the operator to the special 'm' operator that we'll deal with in rpn_calc */
                *tok = 'm';
            }

            /* while there is an operator at the top of the operator stack with
			   greater than or equal to precedence: */
            while (((op = stack_top(s)) != NULL) && operator_is_preceding(*op, *tok)) {
                /* pop operators from the operator stack, onto the output queue; */
                queue_enqueue(q, create_char_data(*(char *)stack_pop(s)));
            }
            /* push the read operator onto the operator stack. */
            stack_push(s, (void *)tok);
            break;
        /* if the token is a left bracket (i.e. "("), then: */
        case TOKEN_LBRACKET:
            /* special case: last token was a number or rbracket and we have lbracket now */
            if (tok_last == TOKEN_NUMBER || tok_last == TOKEN_RBRACKET) {
                /* push a * sign with high precendence */
                stack_push(s, (void *)&mul);
            }
            /* push it onto the operator stack */
            stack_push(s, tok);
            break;
        /* if the token is a right bracket (i.e. ")"), then: */
        case TOKEN_RBRACKET:
            /* while the operator at the top of the operator stack is not a left bracket: */
            while (((op = stack_top(s)) != NULL) && *op != '(') {
                /* pop operators from the operator stack onto the output queue. */
                queue_enqueue(q, create_char_data(*(char *)stack_pop(s)));
            }
            /* if the stack runs out without finding a left bracket, then there are
		       mismatched parentheses. */
		    if (op == NULL || (op != NULL && *op != '(')) {
		        /* mismatched parentheses */
		        printf("! mismatched parentheses; extra )\n");
		        goto err_cleanup;
		    }
		    /* pop the left bracket from the stack. */
	        stack_pop(s);

            /* check if stack top is a function and if so, pop it */
            if (stack_top(s) != NULL && *((char *)stack_top(s)) == '\0') {
                /* this was a function */
                char *ps;
                void *p;

                /* pop item from stack */
                ps = (char *)stack_pop(s);

                /* remove leading null */
                memmove(ps, ps+1, strlen(ps+1)+1);

                /* fetch function arity */
                arn = stack_pop(arity);

                /* create function data */
                p = create_function_data(*arn, ps);
                free(ps);
                free(arn);

                /* enqueue */
                queue_enqueue(q, p);
            }
            break;
        case TOKEN_FUNCTION:
            /* special case: last token was a number or rbracket and we have variable now */
            if (tok_last == TOKEN_NUMBER || tok_last == TOKEN_RBRACKET) {
                /* push a * sign with high precendence */
                stack_push(s, (void *)&mul);
            }

            len = strlen(tok);
            op = calloc(len + 2, sizeof(char));
            op[0] = '\0';
            op[len] = '\0';
            memcpy(op+1, tok, len);
            stack_push(s, op);

            arn = malloc(sizeof(int));
            *arn = 1;
            stack_push(arity, arn);
            break;
        case TOKEN_COMMA:
            while (((op = stack_top(s)) != NULL) && *op != ',' && *op != '(') {
                /* pop operators from the operator stack onto the output queue. */
                queue_enqueue(q, create_char_data(*(char *)stack_pop(s)));
            }
            if (*op == ',') stack_pop(s);
            stack_push(s, &comma);

            arn = stack_pop(arity);
            (*arn)++;
            stack_push(arity, arn);
            break;
        case TOKEN_VARIABLE:
            /* special case: last token was a number or rbracket and we have variable now */
            if (tok_last == TOKEN_NUMBER || tok_last == TOKEN_RBRACKET) {
                /* push a * sign with high precendence */
                stack_push(s, (void *)&mul);
            }
            queue_enqueue(q, create_var_data(tok));
            break;
        default:
            break;
        }
        tok_last = tkc->type;
    }
    
    /* if there are no more tokens to read: */
    if (tkc->type == TOKEN_END) {
        /* while there are still operator tokens on the stack: */
        while (((op = stack_top(s)) != NULL) && *op != '(') {
            /* pop the operator onto the output queue. */
            queue_enqueue(q, create_char_data(*(char *)stack_pop(s)));
        }
        /* if the operator token on the top of the stack is a bracket, then
		there are mismatched parentheses. */
		if (op != NULL && *op == '(') {
            printf("! mismatched parentheses; extra (\n");
            goto err_cleanup;
		}
    } else {
        printf("! unknown character `%c` in equation\n", *(tkc->pos));
        goto err_cleanup;
    }

    stack_destroy(s);
    stack_destroy(arity);
    tokenizer_destroy(tkc);
    free(newstr);
    return q;

    err_cleanup:
    stack_foreach(s, syard_string_cleanup, NULL);
    stack_destroy(s);
    stack_foreach(arity, syard_queue_cleanup, NULL);
    stack_destroy(arity);
    tokenizer_destroy(tkc);
    queue_foreach(q, syard_queue_cleanup, NULL);
    queue_destroy(q);
    free(newstr);
    return NULL;
}
示例#9
0
文件: bfs.c 项目: boosheng/masterca
int bfs(Graph *graph, BfsVertex *start, List *hops) {

Queue              queue;

AdjList            *adjlist,
                   *clr_adjlist;

BfsVertex          *clr_vertex,
                   *adj_vertex;

ListElmt           *element,
                   *member;

/*****************************************************************************
*                                                                            *
*  Initialize all of the vertices in the graph.                              *
*                                                                            *
*****************************************************************************/

for (element = list_head(&graph_adjlists(graph)); element != NULL; element =
   list_next(element)) {

   clr_vertex = ((AdjList *)list_data(element))->vertex;

   if (graph->match(clr_vertex, start)) {

      /***********************************************************************
      *                                                                      *
      *  Initialize the start vertex.                                        *
      *                                                                      *
      ***********************************************************************/

      clr_vertex->color = gray;
      clr_vertex->hops = 0;

      }

   else {

      /***********************************************************************
      *                                                                      *
      *  Initialize vertices other than the start vertex.                    *
      *                                                                      *
      ***********************************************************************/

      clr_vertex->color = white;
      clr_vertex->hops = -1;

   }

}

/*****************************************************************************
*                                                                            *
*  Initialize the queue with the adjacency list of the start vertex.         *
*                                                                            *
*****************************************************************************/

queue_init(&queue, NULL);

if (graph_adjlist(graph, start, &clr_adjlist) != 0) {

   queue_destroy(&queue);
   return -1;

}

if (queue_enqueue(&queue, clr_adjlist) != 0) {

   queue_destroy(&queue);
   return -1;

}

/*****************************************************************************
*                                                                            *
*  Perform breadth-first search.                                             *
*                                                                            *
*****************************************************************************/

while (queue_size(&queue) > 0) {

   adjlist = queue_peek(&queue);

   /**************************************************************************
   *                                                                         *
   *  Traverse each vertex in the current adjacency list.                    *
   *                                                                         *
   **************************************************************************/

   for (member = list_head(&adjlist->adjacent); member != NULL; member =
      list_next(member)) {

      adj_vertex = list_data(member);

      /***********************************************************************
      *                                                                      *
      *  Determine the color of the next adjacent vertex.                    *
      *                                                                      *
      ***********************************************************************/

      if (graph_adjlist(graph, adj_vertex, &clr_adjlist) != 0) {

         queue_destroy(&queue);
         return -1;

      }

      clr_vertex = clr_adjlist->vertex;

      /***********************************************************************
      *                                                                      *
      *  Color each white vertex gray and enqueue its adjacency list.        *
      *                                                                      *
      ***********************************************************************/

      if (clr_vertex->color == white) {

         clr_vertex->color = gray;
         clr_vertex->hops = ((BfsVertex *)adjlist->vertex)->hops + 1;

         if (queue_enqueue(&queue, clr_adjlist) != 0) {

            queue_destroy(&queue);
            return -1;

         }

      }

   }

   /**************************************************************************
   *                                                                         *
   *  Dequeue the current adjacency list and color its vertex black.         *
   *                                                                         *
   **************************************************************************/

   if (queue_dequeue(&queue, (void **)&adjlist) == 0) {

      ((BfsVertex *)adjlist->vertex)->color = black;

      }

   else {

      queue_destroy(&queue);
      return -1;

   }

}

queue_destroy(&queue);

/*****************************************************************************
*                                                                            *
*  Pass back the hop count for each vertex in a list.                        *
*                                                                            *
*****************************************************************************/

list_init(hops, NULL);

for (element = list_head(&graph_adjlists(graph)); element != NULL; element =
   list_next(element)) {

   /**************************************************************************
   *                                                                         *
   *  Skip vertices that were not visited (those with hop counts of -1).     *
   *                                                                         *
   **************************************************************************/

   clr_vertex = ((AdjList *)list_data(element))->vertex;

   if (clr_vertex->hops != -1) {

      if (list_ins_next(hops, list_tail(hops), clr_vertex) != 0) {

         list_destroy(hops);
         return -1;

      }

   }

}

return 0;

}
int morse_convBinaryToMorse (BisTree *checkMap, char *binaryInputString, int binarySequenceLen,
    							char *morseOutputString, int *morseSequenceLen)
{

	Queue binaryCharQueue;

	register int globalInputIndex;
	register int bufferCounter;
	int globalOutputCounter;

	int searchResult;
	int returnResult;

	char currentInputChar;
	char binaryBuffer[20];
	char *binaryDigit, *morseCharToken;

	globalInputIndex = 0;
	bufferCounter = 0;
	globalOutputCounter = 0;
	returnResult = 0;
	queue_init(&binaryCharQueue, 0);

	while (globalInputIndex < binarySequenceLen) {

		currentInputChar = *(binaryInputString + globalInputIndex);

		
		/* Enqueue the binary character at hand to the Queue for later processing */
		queue_enqueue(&binaryCharQueue, (void*) (binaryInputString + globalInputIndex));
		globalInputIndex = globalInputIndex + 1;

		
		/* If current input character at hand is a '0', we have got a full segment */
		/* In this case, pop all the characters from the Queue and get the Morse character */
		if (currentInputChar == '0') {

		
			/* Dequeue all binary symbols from the Queue and store them to buffer */
			while (queue_size(&binaryCharQueue) > 0) {

				queue_dequeue(&binaryCharQueue, (void**) &binaryDigit);
				*(binaryBuffer + bufferCounter) = *binaryDigit;
				bufferCounter = bufferCounter + 1;
			}

			
			/* At the end of our buffer, place a NUL character to mark end of string */
			*(binaryBuffer + bufferCounter) = '\0';
			
			
			/* Search for the string from buffer for its corresponding Morse character */
			searchResult = bst_findElement(checkMap, (void*) binaryBuffer, (void**) &morseCharToken);
			returnResult = searchResult;

			
			/* If we cant find a Morse character for our binary string, its an error */
			if (returnResult == -1) goto EXIT_FUNCTION;

			
			/* Write the Morse character we have got to the Output stream */
			*(morseOutputString + globalOutputCounter) = *morseCharToken;
			globalOutputCounter++;

			/* printf("Chunk string in buffer: %s, Morse: %c\n", binaryBuffer, *morseCharToken);*/

			
			/* Clear the buffer, it is enough to set the buffer length to 0 */
			bufferCounter = 0;
			
		} /* End of IF condition (We just processed a single Morse character) */
		
		/* Start again */
	}
	
	
	/* Check the size of our temporary binary symbol queue */
	/* If elements still exist inside the queue, then it is considered an error */
	if (queue_size(&binaryCharQueue) > 0) {
		returnResult = -1;
		goto EXIT_FUNCTION;
	}

	*morseSequenceLen = globalOutputCounter;

EXIT_FUNCTION:

	/* Clean up and return to the caller */
	queue_destroy(&binaryCharQueue);
	return returnResult;

}
示例#11
0
void serial_put(uint8_t c){
  /* Fiquem un element al principi de la cua de transmissio */
  while (queue_is_full(&tx));
  queue_enqueue(&tx,c);
  UCSR0B |= (_BV(UDRIE0));
}
示例#12
0
/**
 * Code for the consumer threads. They take the orders and process them. The
 * argument to this function should be a null-terminated string representing the
 * category name for this thread.
 */
void *consumer_thread(void *args) {
    char *category, *input;
    customer_t *customer;
    order_t *order;
    receipt_t *receipt;

    // Get the category for this thread.
    input = (char *) args;
    category = (char *) malloc(strlen(input) + 1);
    strcpy(category, input);

    while (!is_done || !queue_isempty(queue)) {
        // We wait until there is something in the queue
        pthread_mutex_lock(&queue->mutex);

        if (!is_done && queue_isempty(queue)) {
            pthread_cond_wait(&queue->nonempty, &queue->mutex);
        }

        if (is_done && queue_isempty(queue)) {
            // No more orders to process. Exit this thread.
            pthread_mutex_unlock(&queue->mutex);
            return NULL;
        }
        else if (queue_isempty(queue)) {
            // The queue is empty again.
            pthread_mutex_unlock(&queue->mutex);
            sched_yield();
            continue;
        }

        order = (order_t *) queue_peek(queue);
        if (strcmp(order->category, category) != 0) {
            // This book is not in our category.
            pthread_mutex_unlock(&queue->mutex);
            sched_yield();
        }
        else {
            // Process the order.
            order = (order_t *) queue_dequeue(queue);
            customer = database_retrieve_customer(customerDatabase,
                                                  order->customer_id);
            if (!customer) {
                // Invalid customer ID
                fprintf(stderr, "There is no customer in the database with"
                        "customer ID %d.\n", order->customer_id);
            }
            else {
                receipt = receipt_create(order->title,
                                         order->price,
                                         customer->credit_limit - order->price);
                if (customer->credit_limit < order->price) {
                    // Insufficient funds.
                    printf("%s has insufficient funds for a purchase.\n"
                           "\tBook: %s\n\tRemaining credit: $%.2f\n\n",
                           customer->name,
                           order->title,
                           customer->credit_limit);
                    queue_enqueue(customer->failed_orders, receipt);
                }
                else {
                    // Subtract price from remaining credit
                    customer->credit_limit -= order->price;
                    printf("Customer %s has made a successful purchase!\n"
                           "\tBook: %s\n\tPrice: $%.2f\n"
                           "\tRemaining credit: $%.2f\n\n",
                           customer->name,
                           order->title,
                           order->price,
                           customer->credit_limit);
                    queue_enqueue(customer->successful_orders, receipt);
                }
            }
            order_destroy(order);
            pthread_mutex_unlock(&queue->mutex);
        }
    }

    free(category);
    return NULL;
}
示例#13
0
文件: event.c 项目: ekiru/amud
int event_queue(event * ev) {
	return queue_enqueue(&ev_queue, (void *) ev);
}
示例#14
0
/* 主函数 */
int main (int argc, char **argv) {
  Queue queue;
  int *data, i;

  printf("初始化队列\n");
  queue_init(&queue, free);
  print_queue(&queue);

  printf("入队 10 个元素\n");
  for (i = 0; i < 10; i++) {
    if ((data =(int *) malloc(sizeof(int))) == NULL)
      return 1;
    *data = i + 1;
    if (queue_enqueue(&queue, data) != 0)
      return 1;
  }
  print_queue(&queue);

  printf("出队 5 个元素\n");
  for (i = 0; i < 5; i++) {
    if (queue_dequeue(&queue, (void **) &data) == 0)
      free(data);
    else
      return 1;
  }
  print_queue(&queue);

  printf("入队 100 和 200\n");
  if ((data =(int *) malloc(sizeof(int))) == NULL)
    return 1;
  *data = 100;
  if (queue_enqueue(&queue, data) != 0)
    return 1;
  if ((data =(int *) malloc(sizeof(int))) == NULL)
    return 1;
  *data = 200;
  if (queue_enqueue(&queue, data) != 0)
    return 1;
  print_queue(&queue);

  if ((data = queue_peek(&queue)) != NULL)
    printf("检查队列顶...值=%d\n", *data);
  else
    printf("检查队列顶...值=NULL\n");
  print_queue(&queue);

  printf("出队所有元素\n");
  while (queue_size(&queue) > 0) {
    if (queue_dequeue(&queue, (void **) &data) == 0)
      free(data);
  }
  if ((data = queue_peek(&queue)) != NULL)
    printf("检查空队列...值=%d\n", *data);
  else
    printf("检查空队列...值=NULL\n");
  print_queue(&queue);

  printf("销毁队列\n");
  queue_destroy(&queue);

  return 0;
}
示例#15
0
void iguana_acceptloop(void *args)
{
    struct iguana_peer *addr;
    struct iguana_info *coin = args;
    struct pollfd pfd;
    int32_t sock;
    struct iguana_accept *ptr;
    uint16_t port = coin->chain->portp2p;
    socklen_t clilen;
    struct sockaddr_in cli_addr;
    char ipaddr[64];
    uint32_t i,ipbits,flag;
    if ( coin->peers == 0 )
        return;
    while ( (coin->bindsock= iguana_socket(1,"0.0.0.0",port)) < 0 )
    {
        if ( coin->peers->localaddr != 0 )
        {
            printf("another daemon running, no need to have iguana accept connections\n");
            return;
        }
        //if ( port != IGUANA_RPCPORT )
        //    return;
        sleep(5);
    }
    printf(">>>>>>>>>>>>>>>> iguana_bindloop 127.0.0.1:%d bind sock.%d\n",port,coin->bindsock);
    printf("START ACCEPTING\n");
    while ( coin->bindsock >= 0 )
    {
        memset(&pfd,0,sizeof(pfd));
        pfd.fd = coin->bindsock;
        pfd.events = POLLIN;
        if ( poll(&pfd,1,100) <= 0 )
            continue;
        clilen = sizeof(cli_addr);
        //printf("ACCEPT (%s:%d) on sock.%d\n","127.0.0.1",coin->chain->portp2p,coin->bindsock);
        sock = accept(coin->bindsock,(struct sockaddr *)&cli_addr,&clilen);
        if ( sock < 0 )
        {
            printf("ERROR on accept bindsock.%d errno.%d (%s)\n",coin->bindsock,errno,strerror(errno));
            continue;
        }
        memcpy(&ipbits,&cli_addr.sin_addr.s_addr,sizeof(ipbits));
        expand_ipbits(ipaddr,ipbits);
        printf("incoming (%s:%u)\n",ipaddr,cli_addr.sin_port);
        for (i=flag=0; i<IGUANA_MAXPEERS; i++)
        {
            if ( coin->peers->active[i].ipbits == (uint32_t)ipbits && coin->peers->active[i].usock >= 0 )
            {
                printf("found existing peer.(%s) in slot[%d]\n",ipaddr,i);
                close(coin->peers->active[i].usock);
                coin->peers->active[i].dead = 0;
                coin->peers->active[i].usock = sock;
                coin->peers->active[i].A.port = cli_addr.sin_port;
                coin->peers->active[i].ready = (uint32_t)time(NULL);
                flag = 1;
                //instantdex_peerhas_clear(coin,&coin->peers->active[i]);
                //iguana_iAkill(coin,&coin->peers->active[i],0);
                //sleep(1);
                break;
            }
        }
        if ( flag != 0 )
            continue;
        printf("NEWSOCK.%d for %x (%s)\n",sock,ipbits,ipaddr);
        /*if ( (uint32_t)ipbits == myinfo->myaddr.myipbits )
        {

        }*/
        if ( (addr= iguana_peerslot(coin,ipbits,1)) == 0 )
        {
            ptr = mycalloc('a',1,sizeof(*ptr));
            strcpy(ptr->ipaddr,ipaddr);
            ptr->ipbits = ipbits;
            ptr->sock = sock;
            ptr->port = cli_addr.sin_port;
            printf("queue PENDING ACCEPTS\n");
            queue_enqueue("acceptQ",&coin->acceptQ,&ptr->DL,0);
        }
        else
        {
            printf("LAUNCH DEDICATED THREAD for %s:%u\n",ipaddr,cli_addr.sin_port);
            addr->usock = sock;
            addr->dead = 0;
            addr->A.port = cli_addr.sin_port;
            strcpy(addr->symbol,coin->symbol);
            iguana_launch(coin,"accept",iguana_dedicatedglue,addr,IGUANA_CONNTHREAD);
            //iguana_dedicatedloop(coin,addr);
        }
    }
}
示例#16
0
文件: server.c 项目: amshah4/cs241mpx
/* function for pthread_create() to call every time connection is
 * accepted. Consists of part 3 of MP8
 *
 * @param - pointer to an integer returned by accept representing a
 * 			new socket fd to send()/recv() from
 * @return - NULL
 */
void* handleConnection(void *clifd)
{
	int clientfd=*((int*)clifd);
	int keepReceiving, connectionIsAlive=1;	//bools
	unsigned int len;


	while(connectionIsAlive)
	{
		len=0;
		keepReceiving=1;
		char buffer[4096];


		//PART 3a
		while(keepReceiving)
		{
			len+=recv(clientfd, &(buffer[len]), 4096-len, 0);

			if(len>=4 &&	buffer[len-4]=='\r' &&
							buffer[len-3]=='\n' &&
							buffer[len-2]=='\r' &&
							buffer[len-1]=='\n')//if finished receiving, end loop
			{
				keepReceiving=0;
			}
			if(len==0)//if recv() returned 0, connection was closed
			{
				keepReceiving=0;
				connectionIsAlive=0;
			}
		}
		buffer[len]='\0';


		if(connectionIsAlive)
		{
			unsigned int i=0, j;				//indexes
			int notEOLine=1;
			queue_t parsedHeader;
			queue_init(&parsedHeader);


			//PART 3b
			while(i<len)
			{
				char lineBuffer[4096];
				j=0;
				notEOLine=1;


				while(notEOLine)
				{
					lineBuffer[j]=buffer[i];
					if(lineBuffer[j]=='\n')
						notEOLine=0;
					j++;
					i++;
				}
				lineBuffer[j]='\0';

				char *temp=malloc(1024*sizeof(char));
				if(queue_size(&parsedHeader)==0)//if request line
				{
					strcpy(temp, lineBuffer);
					temp[strlen(temp)-2]='\0';
					strcpy(temp, process_http_header_request(temp));
				}
				else
				{
					strcpy(temp, lineBuffer);
				}
				queue_enqueue(&parsedHeader, ((void*)temp));
			}



			//PART 3cdef
			char filename[1024];
			filename[0]='\0';
			strcat(filename, "web");
			FILE *file=NULL;

			char responseln[1024];
			responseln[0]='\0';
			char contentType[1024];
			contentType[0]='\0';
			char contentLength[1024];
			contentLength[0]='\0';
			char connection[1024];
			connection[0]='\0';
			char *content=malloc(4096*sizeof(char));
			content[0]='\0';


			//Set responseln, contentType, contentLength, and content
			if(((char*)queue_at(&parsedHeader, 0))==NULL)	//501 Response
			{
				//501
				sprintf(responseln, "HTTP/1.1 501 %s\r\n", HTTP_501_STRING);
				strcat(contentType, "Content-Type: text/html\r\n");
				sprintf(contentLength, "Content-Length: %d\r\n", (unsigned int)strlen(HTTP_501_CONTENT));
				strcat(content, HTTP_501_CONTENT);
			}
			else
			{
				if(strcmp(((char*)queue_at(&parsedHeader, 0)), "/")==0)
				{
					strcat(filename, "/index.html");
				}
				else
				{
					strcat(filename, ((char*)queue_at(&parsedHeader, 0)));
				}
				file=fopen(filename, "r");

				if(file==NULL)
				{
					//404
					sprintf(responseln, "HTTP/1.1 404 %s\r\n", HTTP_404_STRING);
					strcat(contentType, "Content-Type: text/html\r\n");
					sprintf(contentLength, "Content-Length: %d\r\n", (unsigned int)strlen(HTTP_404_CONTENT));
					strcat(content, HTTP_404_CONTENT);
				}
				else
				{
					//200
					sprintf(responseln, "HTTP/1.1 200 %s\r\n", HTTP_200_STRING);

					int size=strlen(filename);
					char extention[4];
					extention[0]=filename[size-3];
					extention[1]=filename[size-2];
					extention[2]=filename[size-1];
					extention[3]='\0';
					if(strcmp(extention, "tml")==0)
					{
						strcat(contentType, "Content-Type: text/html\r\n");
					}
					else if(strcmp(extention, "css")==0)
					{
						strcat(contentType, "Content-Type: text/css\r\n");
					}
					else if(strcmp(extention, "jpg")==0)
					{
						strcat(contentType, "Content-Type: image/jpeg\r\n");
					}
					else if(strcmp(extention, "png")==0)
					{
						strcat(contentType, "Content-Type: image/png\r\n");
					}
					else
					{
						strcat(contentType, "Content-Type: text/plain\r\n");
					}

					fseek(file, 0, SEEK_END);
					size=ftell(file);
					fseek(file, 0, SEEK_SET);
					sprintf(contentLength, "Content-Length: %d\r\n", size);

					free(content);
					content=malloc((size+1)*sizeof(char));
					content[0]='\0';
					char line[size];
					while(fgets(line, size, file) != NULL)
					{
						strcat(content, line);
					}
				}
			}

			i=0;
			while(i<((unsigned int)queue_size(&parsedHeader)))
			{
				if(strcasecmp(((char*)queue_at(&parsedHeader, i)), "Connection: Keep-Alive\r\n")==0)
				{
					strcat(connection, "Connection: Keep-Alive\r\n\r\n");
				}


				i++;
			}
			if(strlen(connection)==0)
			{
				strcat(connection, "Connection: close\r\n\r\n");
				connectionIsAlive=0;
			}


			//At this point, all parts of the packet are finished. Time to combine and send()
			char *packet=malloc((	strlen(responseln) +
									strlen(contentType) +
									strlen(contentLength) +
									strlen(connection) +
									strlen(content) +
									1)*sizeof(char));
			sprintf(packet, "%s%s%s%s%s", responseln, contentType, contentLength, connection, content);
			send(clientfd, packet, strlen(packet)*sizeof(char), 0);


			//CLEANUP
			while(queue_size(&parsedHeader))
			{
				free(queue_dequeue(&parsedHeader));
			}
			queue_destroy(&parsedHeader);
			free(content);
			free(packet);
		}
	}


	close(clientfd);
	unsigned int i;

	//CRITICAL ZONE
	pthread_mutex_lock(lock);
	for(i=0; i<queue_size(clients); i++)
	{
		if(*((int*)queue_at(clients, i))==clientfd)
		{
			free(queue_remove_at(clients, i));
		}
	}
	pthread_mutex_unlock(lock);
	//END CRITICAL ZONE

	return NULL;
}
示例#17
0
void* process_tasks(void* id_ptr)
{
	int id = *((int *)id_ptr) + 1;
	printf("Thread started: %i\n", id);
	task_t t;

	while(1) {
		// Get the lock
		pthread_mutex_lock(&mutex);

		// Get task from queue
		if (!queue_is_empty(&queue_gold)) {
			// Check if there is a gold task
			queue_dequeue(&queue_gold, &t);
		} else if (!queue_is_empty(&queue_silver)
				   && (queue_is_empty(&queue_bronze) || silver_count < MAX_SILVER_BEFORE_BRONZE)) {
			silver_count++;
			queue_dequeue(&queue_silver, &t);
		} else if (!queue_is_empty(&queue_bronze)) {
			silver_count = 0;
			queue_dequeue(&queue_bronze, &t);
		} else {
			// We are done, so release lock and allocated memory
			pthread_mutex_unlock(&mutex);
			free(id_ptr);
			return NULL;
		}

		// Release the lock
		pthread_mutex_unlock(&mutex);

		// Process task
		int service_time;
		queue_t* queue;
		switch(t.priority_level) {
			case PRIORITY_LEVEL_GOLD:
				queue = &queue_gold;
				service_time = t.remaining_time;
				break;
			case PRIORITY_LEVEL_SILVER:
				queue = &queue_silver;
				if (t.remaining_time > MAX_SERVICE_TIME_SILVER) {
					service_time = MAX_SERVICE_TIME_SILVER;
				} else {
					service_time = t.remaining_time;
				}
				break;
			case PRIORITY_LEVEL_BRONZE:
			default:
				queue = &queue_bronze;
				if (t.remaining_time > MAX_SERVICE_TIME_BRONZE) {
					service_time = MAX_SERVICE_TIME_BRONZE;
				} else {
					service_time = t.remaining_time;
				}
				break;
		}
		
		// Process task
		printf("Thread %d: service_time=%ims, task={id=%i, priority=%s, remaining=%ims, initial_total=%ims} \n", id, service_time, t.id, priorityLevelToString(t.priority_level), t.remaining_time, t.total_time);
		usleep(service_time * 1000);
		
		// Put back in queue if not finished
		if (t.remaining_time > service_time) {
			t.remaining_time -= service_time;
			pthread_mutex_lock(&mutex);
			queue_enqueue(queue, t);
			pthread_mutex_unlock(&mutex);		
		} else {
			// Task finished, find turn-around time
			struct timeval end_time;
			gettimeofday(&end_time, NULL);
			
			int turn_around_time = (int)((end_time.tv_sec - t.start_time.tv_sec) * 1000) + ((end_time.tv_usec - t.start_time.tv_usec) / 1000);
			printf("---Task Complete: turn_around_time = %dms, task={id=%i, initial_total=%ims}---\n", turn_around_time, t.id, t.total_time);
		}
	}
}
示例#18
0
文件: server.c 项目: amshah4/cs241mpx
int main(int argc, char **argv)
{
	int sockfd;
	tids=malloc(sizeof(queue_t));
	clients=malloc(sizeof(queue_t));
	queue_init(tids);
	queue_init(clients);
	struct addrinfo hints, *result;


	pthread_mutexattr_t attr;
	pthread_mutexattr_init(&attr);
	lock=malloc(sizeof(pthread_mutex_t));
	pthread_mutex_init(lock, &attr);
	pthread_mutexattr_destroy(&attr);


	struct sigaction cc;	//ctrl+c handlerer
	cc.sa_handler=handlecc;
	cc.sa_flags=0;
	sigemptyset(&cc.sa_mask);
	sigaction(SIGINT, &cc, NULL);


	//PART 1
	sockfd=socket(AF_INET/*ipv4*/, SOCK_STREAM/*TCP*/, 0);
	if(sockfd==-1)
	{
		perror("socket() failed\n");
		exit(1);
	}

	//creates struct for bind;
	hints.ai_family=AF_INET;
	hints.ai_socktype=SOCK_STREAM;
	hints.ai_flags=AI_PASSIVE;
	if(getaddrinfo(NULL, argv[1]/*port*/, &hints, &result)!=0)
	{
		perror("getadderinfo() failed\n");
		exit(1);
	}

	if(bind(sockfd, result->ai_addr, result->ai_addrlen) != 0)
	{
		perror("bind\n");
		exit(1);
	}

	if(listen(sockfd, 10)!=0)
	{
		perror("listen() failed\n");
		exit(1);
	}
	free(result);


	//PART 2
	while(1)
	{
		pthread_t *temp=malloc(sizeof(pthread_t));
		int *tempfd=malloc(sizeof(int));

		*tempfd=accept(sockfd, NULL, NULL);
		pthread_create(temp, NULL, handleConnection, ((void*)tempfd));

		queue_enqueue(tids, ((void*)temp));
		queue_enqueue(clients, ((void*)tempfd));
	}


	return 0;
}
示例#19
0
int DecodeVideo::decode(uint8_t * input, unsigned int size, unsigned int timestamp,
                        queue_t * outQueue, bool * gotFrame,
                        QueueExtraData * extraData)
{
    if (!(_flags & FLAG_OPENED)) {
        NEW_ERROR(E_DECODE_NOT_OPENED, "");
        return -1;
    }
    if (!outQueue || !input || !size) {
        NEW_ERROR(E_COMMON_NULL_PARAMETER, "outQueue | input | size");
        return -1;
    }

    uint32_t inbufSize = size;
    uint8_t * outbuf;
    int gotFrameInt;
    int outbufSize;
    QueueExtraDataVideo extraNew;

    if (gotFrame) {
        *gotFrame = false;
    }

    // só pode começar a decodificação em um quadro I
    if (_needFrameI) {
        if (_IsFrameI(&input, &inbufSize)) {
            _needFrameI = false;
        } else {
            NEW_WARNING(E_DECODE_WAITING_FRAME_I, "Aguardando um frame I");
            return -1;
        }
    }

    // fica decodificando o buffer até que encontre um frame completo ou até
    // que acabe o buffer disponível
    _codecCtxMutex.lock();
    int usedTotal = 0;
    while ((uint32_t)usedTotal < inbufSize) {
        AVPacket packet;
        av_init_packet(&packet);
        packet.data = input + usedTotal;
        packet.size = inbufSize - usedTotal;
        gotFrameInt = 0;
        int used = avcodec_decode_video2(_codecCtx, _tempFrame, &gotFrameInt, &packet);
        usedTotal += used;

        // se já usou todo buffer mas não completou o frame, tenta decodificar de novo o mesmo
        // buffer pra tentar pegar o frame. isso é necessário ao decodificar mpeg4
        if (usedTotal == inbufSize && !gotFrameInt && used >= 0) {
            used = avcodec_decode_video2(_codecCtx, _tempFrame, &gotFrameInt, &packet);
        }

        av_free_packet(&packet);

        if (used < 0) {
            NEW_ERROR(E_DECODE_VIDEO, "Falha decodificando video.");
            _codecCtxMutex.unlock();
            return -1;
        }

        if (gotFrameInt) { // pegou frame completo!
            break;
        }
    }
    _codecCtxMutex.unlock();

    // guarda variável de saída
    if (gotFrame) {
        *gotFrame = (gotFrameInt != 0);
    }

    // se não pegou um frame inteiro nem prossegue... retorna o que usou do buffer
    if (!(*gotFrame)) {
        return -1;
    }

    // desentrelaçamento, conversão de pix_fmt, cópia para o buffer de saída
    outbufSize = _PrepareFrame(_tempFrame, &outbuf);
    if (outbufSize <= 0) {
        return -1;
    }

    // coloca os dados na queue
    // obs: só coloca se pegou um frame inteiro
    extraNew =_UpdateExtraData((QueueExtraDataVideo *)extraData);
	#ifdef ANDROID    
	if(queue_length(outQueue) < 5){
	if (queue_enqueue(outQueue, outbuf, outbufSize, timestamp, &extraNew) != E_OK) {
        queue_dealloc(outbuf);
        NEW_ERROR(E_DECODE_ENQUEUE, "");
        return -1;
    }
    } else {
    	queue_dealloc(outbuf);
    }
	#else
	if (queue_enqueue(outQueue, outbuf, outbufSize, timestamp, &extraNew) != E_OK) {
        queue_dealloc(outbuf);
        NEW_ERROR(E_DECODE_ENQUEUE, "");
        return -1;
    }
	#endif

    return usedTotal;
}
示例#20
0
/* TODO avoid allocations for edge_computed and marked */
static void extract(const struct CtGrid3d *grid, const struct Cell *start,
                    const double isovalue, void *vertices, const int v_capacity, int *v_len,
                    void *indices, const int i_capacity, int *i_len,
                    struct CtContinuation3dStat *stat)
{
    int v_len_tmp = 0;
    int i_len_tmp = 0;

    /* use correct spacing and and aspect ratio */
    const float x = grid->header.spacing[0] * grid->header.size[0];
    const float y = grid->header.spacing[1] * grid->header.size[1];
    const float z = grid->header.spacing[2] * grid->header.size[2]; 
    const float max_dim = (x > y) ? (x > z) ? x : z : (y > z) ? y : z;
    const float aspect_x = x / max_dim;
    const float aspect_y = y / max_dim;
    const float aspect_z = z / max_dim;

    struct Queue *queue = queue_create(sizeof(struct Cell));
    queue_enqueue(queue, start);

    /* marked cell surfaces, max. 4 per cell, initially zeroed */
    /* TODO probably don't allocate every time */
    /* TODO 8 cells can be stored per byte */
    char *marked = calloc(4 * (grid->x - 1) * (grid->y - 1) * (grid->z - 1), sizeof(char));

    /* lookup for edges if were computed */
    int *edge_computed = malloc(3 * grid->x * grid->y * grid->z * sizeof(int));
    /* set all to 1s, means not computed */
    memset(edge_computed, 0xFF, 3 * grid->x * grid->y * grid->z * sizeof(int));

    scalar_t h[8];
    struct Vertex vertex;
    struct Cell next_cell;

    while (queue_length(queue)) {
        const struct Cell cell = queue_front(queue, struct Cell);
        queue_dequeue(queue);

        ++stat->visited_cells;

        /* compute case */
        const int c = compute_case(grid, isovalue, cell.x, cell.y, cell.z, h);

        /* get surface */
        const int s = mc_in_edge2surface[c][cell.in_edge];
        const int cell_offset = cell.z * (grid->x - 1) * (grid->y - 1) + cell.y * (grid->x - 1) + cell.x;
        const int surface_id = s >> 8 & 0x0F;

        if (marked[4 * cell_offset + surface_id])
            continue;
    
        marked[4 * cell_offset + surface_id] = 1;

        ++stat->extracted_cells;

        /* extract surface */
        const int start = s & 0x0F;
        const int end = s >> 4 & 0x0F;
        for (int i = start; i < end; ++i) {
            const int index[2] = {mc_edge2indices[mc_edges[c][i]][0], mc_edge2indices[mc_edges[c][i]][1]};
            const float alpha = (isovalue - h[index[0]]) / (h[index[1]] - h[index[0]]);

            const int8_t *v0 = mc_index2vertex[index[0]]; /* lower offset from start */
            const int8_t *v1 = mc_index2vertex[index[1]]; /* higher offset from start */

            /* compute position in edge indices for vertex reduction */
            /* TODO precompute lookup table */
            int edge_offset = 3 * ((v0[2] + cell.z) * grid->x * grid->y +
                                   (v0[1] + cell.y) * grid->x + v0[0] + cell.x);
            if (v0[1] != v1[1])
                edge_offset += 1;
            else if (v0[2] != v1[2])
                edge_offset += 2;

            /* all bits set => not computed */
            if (edge_computed[edge_offset] == ~0) {
                /* interpolate position */
                vertex = ndc_vertex(grid, alpha * (v1[0] + cell.x) + (1.0f - alpha) * (v0[0] + cell.x),
                                    alpha * (v1[1] + cell.y) + (1.0f - alpha) * (v0[1] + cell.y),
                                    alpha * (v1[2] + cell.z) + (1.0f - alpha) * (v0[2] + cell.z),
                                    aspect_x, aspect_y, aspect_z);

                if (v_len_tmp == v_capacity)
                    goto exit;

                memcpy((unsigned char *)vertices + v_len_tmp * sizeof(struct Vertex),
                       &vertex, sizeof(struct Vertex));
                edge_computed[edge_offset] = v_len_tmp++;
            }

            if (i_len_tmp == i_capacity)
                goto exit;
            
            /* TODO batch with memcpy */
            *((unsigned *)indices + i_len_tmp++) = edge_computed[edge_offset];
        }

        /* follow surface */
        for (int i = start; i < end && mc_out_edges[c][i] != -1; ++i) {
            const int out_edge = mc_out_edges[c][i];
            /* came in through this edge, therefore skipping */
            /* TODO problem if it is starting cell and we need go out through in_edge */
            if (out_edge == cell.in_edge)
                continue;

            next_cell.x = mc_out_edge2cell[out_edge][1] + cell.x;
            next_cell.y = mc_out_edge2cell[out_edge][2] + cell.y;
            next_cell.z = mc_out_edge2cell[out_edge][3] + cell.z;
            next_cell.in_edge = mc_out_edge2cell[out_edge][0];

            /* check if lies within boundary */
            if (next_cell.x >= 0 && next_cell.x < grid->x - 1 &&
                next_cell.y >= 0 && next_cell.y < grid->y - 1 &&
                next_cell.z >= 0 && next_cell.z < grid->z - 1) {

                queue_enqueue(queue, &next_cell);
            }
        }
    }

exit:
    *i_len = i_len_tmp;
    *v_len = v_len_tmp;
    stat->vertices_len = v_len_tmp;
    stat->triangles_len = i_len_tmp / 3;
    free(edge_computed);
    free(marked);
    queue_destroy(queue);
}
示例#21
0
/**
 * Entry point to parmake.
 */
int main(int argc, char **argv)
{
	int threads=1;						//working threads, additional to main thread
	char *fname=0;						//makefile name
	char temp=0;						//used for whatever
	char **targets=NULL;				//targets array
	int targetsGiven=0;					//targets count
	queue_init(rules);					//queue initialized
	queue_init(nextRule);				//queue initialized
	queue_init(rulesDup);				//queue initialized
	pthread_t *tid=NULL;				//array of thread IDs
	int i;								//loop iterator variable
	result_t *dummy=NULL;					//dummy variable, just in case
	sem_init(&ruleAvailable, 0, 0);		//semaphore initialized
	lock=PTHREAD_MUTEX_INITIALIZER;		//mutex initialized
	/*threadAvailable*/					//semaphore initialized (later)


	//part1
	while ((temp = getopt(argc, argv, "f:j:")) != -1)
	{
		if(temp=='f')
		{
			fname=optarg;
		}
		else if(temp=='j')
		{
			if(optarg!=0)
				threads=atoi(optarg);
		}
		else	//Use of option other than f and j
		{
			return -1;	//unspecified, so I just did same thing as no make file
		}				//I hate having multiple returns, but its faster for now
	}
	if(fname==0)
	{
		if(access("./makefile", F_OK)==0)
			fname="./makefile";
		else if(access("./Makefile", F_OK)==0)
			fname="./Makefile";
		else
			return -1;	//I hate having multiple returns, but its faster for now
	}
	targetsGiven=argc-optind;
	if(targetsGiven)
	{
		targets=malloc((targetsGiven+1)*sizeof(char*));
		for(i=0; i<targetsGiven; i++)
		{
			targets[i]=argv[optind+i];
		}
		targets[targetsGiven]=NULL;
	}


	//part 2
	parser_parse_makefile(fname, targets, 	parsed_new_target,
											parsed_new_dependency,
											parsed_new_command);


	//part 3 and 4
	tid=malloc(threads*sizeof(pthread_t));
	sem_init(&threadAvailable, 0, threads);

	for(i=0; i<threads; i++)
		pthread_create(&tid[i], NULL, runRule, NULL);

	while(queue_size(rules))
	{
		i=-1;
		int found=0;
		rule_t *temp=NULL;
		while(i<numRules && !found)//numRules is a formality, should always be found
		{
			i++;
			temp=queue_at(q, i);
			found=1;
			if(queue_size(temp->deps)!=0)
			{
				int j;
				int k;
				for(j=0; j<queue_size(rulesDup); j++)
				{
					for(k=0; k<queue_size(temp->deps); k++)
					{
						if(strcmp(queue_at(temp->deps, k), queue_at(rulesDup, j)->target)==0)
						{
							found=0;
						}
					}
				}
			}
		}


		sem_wait(&threadAvailable);

		pthread_mutex_lock(&lock);
		//CRITICAL SECTION
		queue_remove_at(rules, i);
		queue_enqueue(nextRule, temp);
		//END CRITICAL SECTION
		pthread_mutex_unlock(&lock);

		sem_post(&ruleAvailable);
	}

	//set up kickers for threads stuck in wait. Won't always be needed
	for(i=0; i<threads; i++)
	{
		pthread_mutex_lock(&lock);
		//CRITICAL SECTION
		queue_enqueue(nextRule, NULL);
		//END CRITICAL SECTION
		pthread_mutex_unlock(&lock);

		sem_post(&ruleAvailable);//waking up waiting threads to kick them
	}
	//wait for threads to finish
	for(i=0; i<threads; i++)
	{
		pthread_join(tid[i], (void**)&dummy);
	}


	while(queue_size(rulesDup))
	{
		rule_t *temp=queue_dequeue(rulesDup);

		rule_destroy(temp);
		free(temp);
	}
	queue_destroy(rules);
	queue_destroy(nextRule);
	sem_destroy(&threadAvailable);
	sem_destroy(&ruleAvailable);
	pthread_mutex_destroy(&lock);
	if(targetsGiven)
	{
		free(targets);
	}
	free(tid);
	return 0;
}
error dstree__breadthwalk_internal(dstree_t                       *t,
                                   dstree__walk_internal_callback *cb,
                                   void                           *opaque)
{
  typedef struct nodedepth
  {
    dstree__node_t *node;
    int             depth;
  }
  nodedepth;

  error     err;
  queue_t  *queue;
  nodedepth nd;

  if (t == NULL)
    return error_OK;

  queue = queue_create(100, sizeof(nodedepth)); /* FIXME: 100 constant */
  if (queue == NULL)
    return error_OOM;

  assert(t->root);

  nd.node  = t->root;
  nd.depth = 0;

  err = queue_enqueue(queue, &nd);
  if (err)
    return err;

  while (!queue_empty(queue))
  {
    nodedepth ndc;

    err = queue_dequeue(queue, &nd);
    if (err)
      return err;

    err = cb(nd.node, nd.depth, opaque);
    if (err)
      return err;

    ndc.depth = nd.depth + 1;

    if (nd.node->child[0])
    {
      ndc.node = nd.node->child[0];
      err = queue_enqueue(queue, &ndc);
      if (err)
        return err;
    }
    if (nd.node->child[1])
    {
      ndc.node = nd.node->child[1];
      err = queue_enqueue(queue, &ndc);
      if (err)
        return err;
    }
  }

  queue_destroy(queue);

  return error_OK;
}
示例#23
0
void sync_queue_enqueue(struct sync_queue_t* queue, void* value) {
    pthread_mutex_lock(&queue->single_mutex);
    queue_enqueue(&queue->sp, value);
    pthread_cond_signal(&queue->single_condvar);
    pthread_mutex_unlock(&queue->single_mutex);
}
示例#24
0
int main(int argc, char **argv)
{
    if (argc < 2)
    {
	fprintf(stderr, "Usage: ./server PORT\n");
	exit(0);
    }
    int port = atoi(argv[1]);
    if (port <= 0 || port >= 65536)
    {
	fprintf(stderr, "Illegal port number.\n");
	return 1;
    }
	
    int s;

    sock_fd = socket(AF_INET, SOCK_STREAM, 0);

    struct addrinfo hints;
    
    memset(&hints, 0, sizeof(struct addrinfo));
    hints.ai_family = AF_INET;
    hints.ai_socktype = SOCK_STREAM;
    hints.ai_flags = AI_PASSIVE;
    s = getaddrinfo(NULL, argv[1], &hints, &result);
    if (s)
    {
	fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(s));
	exit(1);
    }
    
    if (bind(sock_fd, result->ai_addr, result->ai_addrlen))
    {
	perror("bind failure");
	exit(1);
    }

    if (listen(sock_fd, 10))
    {
	perror("listen failure");
	exit(1);
    }

    signal(SIGINT, handler);
    pthread_mutex_init(&mutex,NULL);
    queue_init(&pthread_queue);
    queue_init(&fd_queue);
    load();
    printf("listening on port %s\n",argv[1]);fflush(stdout);
    
    
    while (1)
    {
	
	int client_fd = accept(sock_fd, NULL, NULL);
	if (client_fd == -1)
	{
	    perror("accept failure");
	}
	else
	{
	    pthread_mutex_lock(&mutex);
	    
	    pthread_t conn;
	    int * pass_fd = malloc(sizeof(int));
	    *pass_fd = client_fd;
	    pthread_create(&conn,NULL,conn_handler,(void *)pass_fd); 
	    queue_enqueue(&pthread_queue, (void *)conn);
	    queue_enqueue(&fd_queue, (void *)( (unsigned long) client_fd));
	    
	}
	pthread_mutex_unlock(&mutex);
	
    }
    return 0;
}
示例#25
0
文件: libjl777.c 项目: apex944/btcd
uint64_t call_SuperNET_broadcast(struct pserver_info *pserver,char *msg,int32_t len,int32_t duration)
{
    int32_t SuperNET_broadcast(char *msg,int32_t duration);
    int32_t SuperNET_narrowcast(char *destip,unsigned char *msg,int32_t len);
    char ip_port[64],*ptr;
    uint64_t txid = 0;
    int32_t port;
    if ( 1 || SUPERNET_PORT != _SUPERNET_PORT )
        return(0);
    if ( Debuglevel > 1 )
        printf("call_SuperNET_broadcast.%p %p len.%d\n",pserver,msg,len);
    txid = calc_txid((uint8_t *)msg,(int32_t)strlen(msg));
    if ( pserver != 0 )
    {
        port = (pserver->p2pport == 0) ? BTCD_PORT : pserver->p2pport;
        //fprintf(stderr,"port.%d\n",port);
        sprintf(ip_port,"%s:%d",pserver->ipaddr,port);
        txid ^= calc_ipbits(pserver->ipaddr);
        if ( Debuglevel > 1 )
        {
            char debugstr[4096];
            init_hexbytes_noT(debugstr,(uint8_t *)msg,len);
            debugstr[32] = 0;
            fprintf(stderr,"%s NARROWCAST.(%s) txid.%llu (%s)\n",pserver->ipaddr,debugstr,(long long)txid,ip_port);
        }
        ptr = calloc(1,64 + sizeof(len) + len + 1);
        memcpy(ptr,&len,sizeof(len));
        memcpy(&ptr[sizeof(len)],ip_port,strlen(ip_port));
        memcpy(&ptr[sizeof(len) + 64],msg,len);
        queue_enqueue(&NarrowQ,ptr);
        return(txid);
    }
    else
    {
        char *cmdstr,NXTaddr[64];
        cJSON *array;
        int32_t valid;
        array = cJSON_Parse(msg);
        if ( array != 0 )
        {
            cmdstr = verify_tokenized_json(0,NXTaddr,&valid,array);
            if ( cmdstr != 0 )
                free(cmdstr);
            free_json(array);
            if ( Debuglevel > 1 )
            {
                char debugstr[4096];
                init_hexbytes_noT(debugstr,(uint8_t *)msg,len);
                debugstr[32] = 0;
                printf("BROADCAST parms.(%s) valid.%d duration.%d txid.%llu len.%d\n",debugstr,valid,duration,(long long)txid,len);
            }
            ptr = calloc(1,sizeof(len) + sizeof(duration) + len);
            memcpy(ptr,&len,sizeof(len));
            memcpy(&ptr[sizeof(len)],&duration,sizeof(duration));
            memcpy(&ptr[sizeof(len) + sizeof(duration)],msg,len);
            ptr[sizeof(len) + sizeof(duration) + len] = 0;
            queue_enqueue(&BroadcastQ,ptr);
            return(txid);
        } else printf("cant broadcast non-JSON.(%s)\n",msg);
    }
    return(txid);
}
示例#26
0
Search* FindPath(Grid* g){
	/*Queue* q=queue_init();
	//printf("1\n");
	Search* se=(Search*)malloc(sizeof(Search));
	//printf("2\n");
	se->s=stack_init();
	//printf("3\n");
	se->Length=0;
	//printf("4\n");
	
	se->ParentR=(int**)malloc(sizeof(int*));
	//printf("5\n");
	int i, j;
	for(i=0;i<g->rows;i++)
	{
		se->ParentR[i]=(int*)malloc(sizeof(int));
		printf("6\n");
		for(j=0;j<g->cols;j++)
		{	
			printf ("test i: %d j: %d\n",i,j);
			se->ParentR[i][j]=-2;
		}
	}
	printf("working here...");
	se->ParentC=(int**)malloc(sizeof(int*));
	printf("7\n");
	for(i=0;i<g->rows;i++)
	{
		se->ParentC[i]=(int*)malloc(sizeof(int));
		printf("8\n");
		for(j=0;j<g->cols;j++)
		{
			se->ParentC[i][j]=-2;
		}
	}

	se->Distance=(int**)malloc(sizeof(int*));
	printf("9\n");
	for(i=0;i<g->rows;i++)
	{
		se->Distance[i]=(int*)malloc(sizeof(int));
		printf("10\n");
		for(j=0;j<g->cols;j++)
		{
			se->Distance[i][j]=MAX_INT;
		}
	}
	
	i=0, j=0;
	int startR, startC;
	for(i=0;i<g->rows;i++)
	{
		for(j=0;j<g->cols;j++)
		{
			if(g->data[i][j]=='S')
			{
				startR=i;
				startC=j;
				break;
			}
		}
	}
	
	se->Distance[startR][startC]=0;
	se->ParentR[startR][startC]=-1;
	se->ParentC[startR][startC]=-1;
	
	queue_enqueue(q, startR, startC);
	
	int *currR, *currC;
	while(queue_size(q)!=0 && g->data[*currR][*currC]!='G')
	{
		queue_enqueue(q, *currR, *currC);
		
		//up
		if(g->data[*currR-1][*currC]==' ' && se->ParentR[*currR-1][*currC]==-2 && se->ParentC[*currR-1][*currC]==-2)
		{
			se->Distance[*currR-1][*currC] = se->Distance[*currR][*currC] + 1;
			se->ParentR[*currR-1][*currC] = *currR;
			se->ParentC[*currR-1][*currC] = *currC;
			queue_enqueue(q, *currR-1, *currC);
		}
		
		//down
		if(g->data[*currR+1][*currC]==' ' && se->ParentR[*currR+1][*currC]==-2 && se->ParentC[*currR+1][*currC]==-2)
		{
			se->Distance[*currR+1][*currC] = se->Distance[*currR][*currC] + 1;
			se->ParentR[*currR+1][*currC] = *currR;
			se->ParentC[*currR+1][*currC] = *currC;
			queue_enqueue(q, *currR+1, *currC);
		}
		
		//left
		if(g->data[*currR][*currC-1]==' ' && se->ParentR[*currR][*currC-1]==-2 && se->ParentC[*currR][*currC-1]==-2)
		{
			se->Distance[*currR][*currC-1] = se->Distance[*currR][*currC] + 1;
			se->ParentR[*currR][*currC-1] = *currR;
			se->ParentC[*currR][*currC-1] = *currC;
			queue_enqueue(q, *currR, *currC-1);
		}
		
		//right
		if(g->data[*currR][*currC+1]==' ' && se->ParentR[*currR][*currC+1]==-2 && se->ParentC[*currR][*currC+1]==-2)
		{
			se->Distance[*currR][*currC+1] = se->Distance[*currR][*currC] + 1;
			se->ParentR[*currR][*currC+1] = *currR;
			se->ParentC[*currR][*currC+1] = *currC;
			queue_enqueue(q, *currR, *currC+1);
		}
	}
	
	if(queue_size==0 && g->data[*currR][*currC]!='G')
	{
		se->Length=-1;
		return se;
	}
	else
	{
		se->Length=se->Distance[*currR][*currC];
		stack_push(se->s, *currR, *currC);
		
		do
		{
			if(*currR!=-1 && *currC!=-1)
			{
				stack_push(se->s, se->ParentR[*currR][*currC], se->ParentC[*currR][*currC]);
			}
			int tempR = *currR, tempC=*currC;
			*currR=se->ParentR[tempR][tempC];
			*currC=se->ParentC[tempR][tempC];	
		}while(*currR!=startR || *currC!=startC);
		
		return se;
	}*/
	Queue* q=queue_init();
	//printf("1\n");
	Search* se=(Search*)malloc(sizeof(Search));
	//printf("2\n");
	se->s=stack_init();
	//printf("3\n");
	se->Length=0;
	//printf("4\n");
	
	int i=0, j=0, rows = g->rows, cols = g->cols;
	
	se->ParentR=(int**)malloc(sizeof(int*)*rows);
	//printf("5\n");
	
	//printf("Here\n");
	//printf("Rows %d\n", rows);
	//printf("i: %d",i);
	
	//system.end(0);
	
	for(i=0;i<rows;i++)
	{
		//break;
		//printf("Rows %d\n", rows);
		
		//system("sleep(1000)");
		//printf("%d\n",i);
		se->ParentR[i]=(int*)malloc(sizeof(int)*cols);
		//printf("6\n");
		//cant access i=1...n
	}
	//printf("Here\n");
	for(i=0;i<rows;i++)
	{
		for(j=0;j<cols;j++)
		{	
			//printf ("test i: %d j: %d\n",i,j);
			//se->ParentR[1][1]=-2;
			se->ParentR[i][j]=-2;
		}
	}
	//printf("working here...");
	se->ParentC=(int**)malloc(sizeof(int*)*rows);
	//printf("7\n");
	for(i=0;i<rows;i++)
	{
		se->ParentC[i]=(int*)malloc(sizeof(int)*cols);
		//printf("8\n");
	}
	for(i=0;i<rows;i++)
	{
		for(j=0;j<cols;j++)
		{
			//printf("%d\n",i);
			se->ParentC[i][j]=-2;
		}
	}
	//printf("Test\n");
	se->Distance=(int**)malloc(sizeof(int*)*rows);
	//printf("9\n");
	
	for(i=0;i<rows;i++)
	{
		se->Distance[i]=(int*)malloc(sizeof(int)*cols);
		//printf("10\n");
		
	}
	
	for(i=0;i<rows;i++)
	{
		for(j=0;j<cols;j++)
		{
			se->Distance[i][j]=MAX_INT;
		}
	}
	
	i=0, j=0;
	int startR, startC;
	for(i=0;i<rows;i++)
	{
		for(j=0;j<cols;j++)
		{
			if(g->data[i][j]=='S')
			{
				startR=i;
				startC=j;
				break;
			}
		}
	}
	
	se->Distance[startR][startC]=0;
	se->ParentR[startR][startC]=-1;
	se->ParentC[startR][startC]=-1;
	//printf("Rows: %d Cols: %d\n",rows,cols);
	//*q = enqueue(*startR, *startC);
	queue_enqueue(q, startR, startC);
	
	int currR, currC;
			//printf("hello\n");
	currR = startR;
	currC = startC;
	//printf("Rows: %d Cols: %d\n",rows,cols);
	//printf("queue size: %d\n",queue_size);
			//printf("hello\n");
	while((queue_size)!=0 && g->data[currR][currC]!='G')
	{

		//printf("Rows: %d Cols: %d\n",rows,cols);
		queue_enqueue(q, currR, currC);
		
		//up
		if(g->data[currR-1][currC]==' ' && se->ParentR[currR-1][currC]==-2 && se->ParentC[currR-1][currC]==-2)
		{
			se->Distance[currR-1][currC] = se->Distance[currR][currC] + 1;
			se->ParentR[currR-1][currC] = currR;
			se->ParentC[currR-1][currC] = currC;
			queue_enqueue(q, currR-1, currC);
		}
		
		//down
		if(g->data[currR+1][currC]==' ' && se->ParentR[currR+1][currC]==-2 && se->ParentC[currR+1][currC]==-2)
		{
			se->Distance[currR+1][currC] = se->Distance[currR][currC] + 1;
			se->ParentR[currR+1][currC] = currR;
			se->ParentC[currR+1][currC] = currC;
			queue_enqueue(q, currR+1, currC);
		}
		
		//left
		if(g->data[currR][currC-1]==' ' && se->ParentR[currR][currC-1]==-2 && se->ParentC[currR][currC-1]==-2)
		{
			se->Distance[currR][currC-1] = se->Distance[currR][currC] + 1;
			se->ParentR[currR][currC-1] = currR;
			se->ParentC[currR][currC-1] = currC;
			queue_enqueue(q, currR, currC-1);
		}
		
		//right
		if(g->data[currR][currC+1]==' ' && se->ParentR[currR][currC+1]==-2 && se->ParentC[currR][currC+1]==-2)
		{
			se->Distance[currR][currC+1] = se->Distance[currR][currC] + 1;
			se->ParentR[currR][currC+1] = currR;
			se->ParentC[currR][currC+1] = currC;
			queue_enqueue(q, currR, currC+1);
		}
	}
	
	if(queue_size==0 && g->data[currR][currC]!='G')
	{
		se->Length=-1;
		return se;
	}
	else
	{
		se->Length=se->Distance[currR][currC];
		stack_push(se->s, se->ParentR[currR][currC], se->ParentC[currR][currC]);
		//se->s->
		do
		{
			if(currR!=-1 && currC!=-1)
			{
				stack_push(se->s, se->ParentR[currR][currC], se->ParentC[currR][currC]);
			}
			int tempR = currR, tempC=currC;
			currR=se->ParentR[tempR][tempC];
			currC=se->ParentC[tempR][tempC];	
		}while(currR!=startR || currC!=startC);
		
		return se;
	}
}
示例#27
0
void sched_sleep_on(queue_t *q) {
  current_thread->state = SLEEPING;
  current_thread->waitchan = q;
  queue_enqueue(q, current_thread);
  sched_switch();
}
示例#28
0
int my_open(char* name, int flags)
{
	if (!Lib_initted) {
		printf("[my_open] Library is not initialized.\n");
		return -1;
	}
	
	if(Open_files >= MAX_OPEN_FILES) {
		printf("[my_open] All slots filled.\n");
		return -1;
	}
	
        if ( myparse(name) != 0 ) {
		printf("[my_open] Malformed pathname.\n");
		return -1;
            
        }
           	

	
	snfs_fhandle_t dir, file_fh;
	unsigned fsize = 0;
	char newfilename[MAX_FILE_NAME_SIZE];
	char newdirname[MAX_PATH_NAME_SIZE];
	char fulldirname[MAX_PATH_NAME_SIZE];
	char *token;
	char *search="/";
	int i=0;
	
	memset(&newfilename,0,MAX_FILE_NAME_SIZE);
	memset(&newdirname,0,MAX_PATH_NAME_SIZE);
	memset(&fulldirname,0,MAX_PATH_NAME_SIZE);

	strcpy(fulldirname,name);
	token = strtok(fulldirname, search);


        while(token != NULL) {
             i++;
	     strcpy(newfilename, token);
            // strncpy(newfilename,token, strlen(token));

             token = strtok(NULL, search);
         } 
         if ( i > 1)
              strncpy(newdirname, name, strlen(name)-(strlen(newfilename)+1));
         else {  
            strncpy(newfilename, &name[1], (strlen(name)-1));
	    newfilename[strlen(newfilename)] = '\0'; //errata 
            strcpy(newdirname, name);   
          }    	

	if(newfilename == NULL) {
		printf("[my_open] Error looking for directory in server.\n");
		return -1;
	}
	
        snfs_call_status_t status = snfs_lookup(name,&file_fh,&fsize);
	 
	
	if (status != STAT_OK) {
			
	         snfs_lookup(newdirname,&dir,&fsize);        
         
                 if (i==1)  //Create a file in Root directory
	             dir = ( snfs_fhandle_t)  1;
	} 
	
	if(flags == O_CREATE && status != STAT_OK) {
		if (snfs_create(dir,newfilename,&file_fh) != STAT_OK) {
			printf("[my_open] Error creating a file in server.\n");
			return -1;
		}
	} else	if (status != STAT_OK) {
		printf("[my_open] Error opening up file.\n");
		return -1;
	}
	
	fd_t fdesc = (fd_t) malloc(sizeof(struct _file_desc));
	fdesc->fileId = file_fh;
	fdesc->size = fsize;
	fdesc->write_offset = 0;
	fdesc->read_offset = 0;
	
	queue_enqueue(Open_files_list, fdesc);
	Open_files++;
	
	return file_fh;
	
}
示例#29
0
文件: imd_ring.c 项目: CBegau/imd
int sp_ring(void) {

  int i, j, k, l, ic, jc, kc, lc;
  cell *p, *q, *pc, *act_cell, *neigh_cell;
  int act_num, neigh_num;
  int r_dist, even = 0;
  neightab *neigh;

  /* Check whether number of vertices in ring is even */
  if ( ( stack_end + 1 ) % 2 == 0 ) 
    even = 1;

  /* Diameter of ring */
  r_dist = ( stack_end + 1 ) / 2;

  /* For half the number of vertices in ring */
  for ( l=0; l<(even==1?r_dist:(r_dist+1)); l++ ) {

    p = stack[l].cl;
    i = stack[l].num;

    /* Compute distances of neighbours of p,i. 
       Breadth-first search, for all atoms */

    /* Initializations */
    for (ic=0; ic < cell_dim.x; ++ic)
      for (jc=0; jc < cell_dim.y; ++jc)
#ifndef TWOD
	for (kc=0; kc < cell_dim.z; ++kc)
#endif
	{
#ifdef TWOD
	  pc = PTR_2D_V(cell_array,ic,jc  ,cell_dim);
#else
	  pc = PTR_3D_V(cell_array,ic,jc,kc,cell_dim);
#endif
	  for ( lc=0; lc<pc->n; lc++ ) 
	    pc->sp_color[lc] = -1;
	}

    p->sp_hops[i]  = 0;
    p->sp_color[i] = 0;

    sp_queue = queue_create(p,i);
    sp_queue_length = 1;

    while ( sp_queue_length > 0 ) {

      queue_dequeue( &sp_queue, &act_cell, &act_num );
      sp_queue_length--;

      /* Actual atom gets black */
      act_cell->sp_color[act_num] = 1;

      /* Neighbour table of actual atom */
      neigh = &act_cell->perm_neightab_array[act_num];
    
      /* For all neighbours of actual atom */
      for ( k=0; k<neigh->n; k++ ) {

	neigh_cell = (cell *) neigh->cl [k];
	neigh_num  = neigh->num [k];
      
	/* If neighbour is white and not farther away than max_length, 
	   enqueue it */
	if ( neigh_cell->sp_color[neigh_num] == -1 
	     && act_cell->sp_hops[act_num] <= (max_length/2 + 1) ) {
	  
	  sp_queue = queue_enqueue( sp_queue, neigh_cell, neigh_num);
	  sp_queue_length++;

	  /* Distance of neighbour atom, which now gets grey */
	  neigh_cell->sp_hops[neigh_num] = act_cell->sp_hops[act_num] + 1;
	  neigh_cell->sp_color[neigh_num] = 0;
	}
      }

    } /* while */

    /* Antipodal atom */
    q = stack[l+r_dist].cl;
    j = stack[l+r_dist].num;
    
    /* Ring is not shortest path */
    if ( q->sp_hops[j] < r_dist ) {
      return 0;
    }
    else if ( even == 0 && l+r_dist+1<=stack_end ) {
      q = stack[l+r_dist+1].cl;
      j = stack[l+r_dist+1].num;
      if  ( q->sp_hops[j] < r_dist )
	return 0;
    }
    
  } /* For antipodal vertices */

  return 1;

}
示例#30
0
/* No More V2*
 * i re-write them all
 */
void queue_test_v2()
{
        int i;
        char ppdata;
        char datas[] = "abcde";
        char datas2[] = "fgh";
        queue_new(que, 5, char);
        for(i = 0; i < 5; i++)
        {
                queue_enqueue(que, &(datas[i]));
                printf("%c enqueued\n",datas[i]);
        }
        for(i = 0; i < 3; i++)
        {
                ppdata = queue_dequeue(que);
                printf("%c dequeued\n",ppdata);
        }
        for(i = 0; i < 3; i++)
        {
                queue_enqueue(que, &(datas2[i]));
                printf("%c enqueued\n",datas2[i]);
        }
        queue_enqueue(que, &(datas[i]));
        printf("%c enqueued\n",datas[i]);
        for(i = 0; i < 5; i++)
        {
                ppdata = queue_dequeue(que);
                printf("%c dequeued\n",ppdata);
        }
        ppdata = queue_dequeue(que);
        printf("%c dequeued\n",ppdata);
        ppdata = queue_dequeue(que);
        printf("%c dequeued\n",ppdata);

        queue_new(otherque, 5, char);
        for(i = 0; i < 5; i++)
        {
                queue_enqueue(otherque, &(datas[i]));
                printf("%c enqueued\n",datas[i]);
        }
        for(i = 0; i < 3; i++)
        {
                ppdata = queue_dequeue(otherque);
                printf("%c dequeued\n",ppdata);
        }
        for(i = 0; i < 3; i++)
        {
                queue_enqueue(otherque, &(datas2[i]));
                printf("%c enqueued\n",datas2[i]);
        }
        queue_enqueue(otherque, &(datas[i]));
        printf("%c enqueued\n",datas[i]);
        for(i = 0; i < 5; i++)
        {
                ppdata = queue_dequeue(otherque);
                printf("%c dequeued\n",ppdata);
        }
        ppdata = queue_dequeue(otherque);
        printf("%c dequeued\n",ppdata);
        ppdata = queue_dequeue(otherque);
        printf("%c dequeued\n",ppdata);
}