static void
sweep_line_init (sweep_line_t	 *sweep_line,
		 rectangle_t	**rectangles,
		 int		  num_rectangles)
{
    _rectangle_sort (rectangles, num_rectangles);
    rectangles[num_rectangles] = NULL;
    sweep_line->rectangles = rectangles;

    sweep_line->head.x = INT32_MIN;
    sweep_line->head.right = NULL;
    sweep_line->head.dir = 0;
    sweep_line->head.next = &sweep_line->tail;
    sweep_line->tail.x = INT32_MAX;
    sweep_line->tail.right = NULL;
    sweep_line->tail.dir = 0;
    sweep_line->tail.prev = &sweep_line->head;

    sweep_line->insert_left = &sweep_line->tail;
    sweep_line->insert_right = &sweep_line->tail;

    sweep_line->current_y = INT32_MIN;
    sweep_line->last_y = INT32_MIN;

    pqueue_init (&sweep_line->pq);
}
Ejemplo n.º 2
0
squeue_t *squeue_create(unsigned int horizon)
{
	if (!horizon)
		horizon = 127; /* makes pqueue allocate 128 elements */

	return pqueue_init(horizon, sq_cmp_pri, sq_get_pri, sq_set_pri, sq_get_pos, sq_set_pos);
}
Ejemplo n.º 3
0
int main(int argc, char ** argv) {
    int nElements, i, q, j;
    struct {
	char (*compare) (pq_element, pq_element);
	uint8_t size;
	uint8_t n_elements;
	pq_element heap[10];
    } pqt;
    
    nElements = argc -1;
    pqueue_init(&pqt, 10, compare);
    for (j=0; j < 10; j++) {
	pqt.heap[j] = -1;
    }
    for (i=0; i < nElements; i++) {
	q = atoi(argv[i+1]);
	printf("%d %d\n", q, pqueue_enqueue(&pqt, q));
	for (j=0; j < 10; j++) {
	    printf("%d ", pqt.heap[j]);
	}
	printf("\n");
    }
    for (i=0; i < nElements; i++) {
    printf("%d\n", pqueue_dequeue(&pqt));
    }
    for (j=0; j < 10; j++) {
	printf("%d ", pqt.heap[j]);
    }
    printf("\n");
}
Ejemplo n.º 4
0
/*
** Load the record ID rid and up to N-1 closest descendants into
** the "ok" table.
*/
void compute_descendants(int rid, int N) {
    Bag seen;
    PQueue queue;
    Stmt ins;
    Stmt q;

    bag_init(&seen);
    pqueue_init(&queue);
    bag_insert(&seen, rid);
    pqueue_insert(&queue, rid, 0.0, 0);
    db_prepare(&ins, "INSERT OR IGNORE INTO ok VALUES(:rid)");
    db_prepare(&q, "SELECT cid, mtime FROM plink WHERE pid=:rid");
    while( (N--)>0 && (rid = pqueue_extract(&queue, 0))!=0 ) {
        db_bind_int(&ins, ":rid", rid);
        db_step(&ins);
        db_reset(&ins);
        db_bind_int(&q, ":rid", rid);
        while( db_step(&q)==SQLITE_ROW ) {
            int pid = db_column_int(&q, 0);
            double mtime = db_column_double(&q, 1);
            if( bag_insert(&seen, pid) ) {
                pqueue_insert(&queue, pid, mtime, 0);
            }
        }
        db_reset(&q);
    }
    bag_clear(&seen);
    pqueue_clear(&queue);
    db_finalize(&ins);
    db_finalize(&q);
}
Ejemplo n.º 5
0
Archivo: proc.c Proyecto: Minjun-Li/xv6
void
pinit(void)
{
  initlock(&ptable.lock, "ptable");
#ifndef __ORIGINAL_SCHED__
  pqueue_init();
#endif
}
Ejemplo n.º 6
0
static void empty_setup()
{
	static int *empty_elts = NULL;

	pqueue_init(&pqueue, sizeof(int), compar, NULL);
	count = 0;
	elts = empty_elts;
}
Ejemplo n.º 7
0
int main(void)
{
	int i;
	int p;

	pqueue_t *pq;
	node_t   *ns;
	node_t   *n;

	/* We will need (N + 1) slots in "pris" vector. Extra one slot for spare
	 * usages. */
	pris = malloc(5 * sizeof(int *));
	for (i = 0; i < 5; i++)
		pris[i] = malloc(2 * sizeof(int));

	pris[0][0] = 4; pris[0][1] = 2;
	pris[1][0] = 3; pris[1][1] = 7;
	pris[2][0] = 3; pris[2][1] = 1;
	pris[3][0] = 5; pris[3][1] = 6;
	p = 4;									/* Initialize spare slot. */

	pq = pqueue_init(10, cmp_pri, get_pri, set_pri, get_pos, set_pos);
	ns = malloc(4 * sizeof(node_t));

	ns[0].pri = 0; ns[0].val = 0; pqueue_insert(pq, &ns[0]);
	ns[1].pri = 1; ns[0].val = 1; pqueue_insert(pq, &ns[1]);
	ns[2].pri = 2; ns[0].val = 2; pqueue_insert(pq, &ns[2]);
	ns[3].pri = 3; ns[0].val = 3; pqueue_insert(pq, &ns[3]);

	printf("initial:\n"); pqueue_print(pq, stdout, pr_node);

	n = pqueue_pop(pq);
	printf("[pop] pri: %d, val: %d, real-pri: [%d %d]\n",
		   n->pri, n->val, pris[n->pri][0], pris[n->pri][1]);
	printf("after first pop:\n"); pqueue_print(pq, stdout, pr_node);

	pris[p][0] = 3; pris[p][1] = 0;
	pqueue_change_priority(pq, p, &ns[3]);	/* 3: (5,6) -> (3,0) */
	p = 3;									/* Move spare slot to 3. */
	printf("after 3: (5,6) -> (3,0):\n"); pqueue_print(pq, stdout, pr_node);

	pris[p][0] = 3; pris[p][1] = -1;
	pqueue_change_priority(pq, p, &ns[0]);	/* 0: (4,2) -> (3,-1) */
	p = 0;									/* Move spare slot to 0. */
	printf("after 0: (4,2) -> (3,-1):\n"); pqueue_print(pq, stdout, pr_node);

	while ((n = pqueue_pop(pq)))
		printf("[pop] pri: %d, val: %d, real-pri: [%d %d]\n",
			   n->pri, n->val, pris[n->pri][0], pris[n->pri][1]);

	pqueue_free(pq);
	free(ns);
	free(pris);

	return 0;
}
Ejemplo n.º 8
0
static void singleton_setup()
{
	static int singleton_elts[] = { 1234 };
	void *ptr;

	pqueue_init(&pqueue, sizeof(int), compar, NULL);
	elts = singleton_elts;
	count = 1;
	pqueue_push(&pqueue, elts);
}
Ejemplo n.º 9
0
static void
test_pqueue_peekmin_empty(void)
{
    struct pqueue q;
    struct pqueue_node nodes[1];
    struct pqueue_entry *min;
    bwputstr(COM2, "test_pqueue_peekmin_empty...");
    pqueue_init(&q, ARRAY_SIZE(nodes), nodes);
    min = pqueue_peekmin(&q);
    assert(min == NULL);
    bwputstr(COM2, "ok\n");
}
Ejemplo n.º 10
0
static void unsorted7_setup()
{
	static int sorted7_elts[] = { 7, 6, 5, 4, 3, 2, 1 };
	int unsorted7_elts[] = { 2, 1, 3, 4, 7, 6, 5 };
	size_t i;

	pqueue_init(&pqueue, sizeof(int), compar, NULL);
	elts = sorted7_elts;
	count = 7;
	
	for (i = 0; i < count; i++)
		pqueue_push(&pqueue, &unsorted7_elts[i]);
}
Ejemplo n.º 11
0
static void sorted5_setup()
{
	static int sorted5_elts[] = { 5, 4, 3, 2, 1 };
	size_t i;
	
	pqueue_init(&pqueue, sizeof(int), compar, NULL);
	elts = sorted5_elts;
	count = 5;
	
	for (i = 0; i < count; i++)
		pqueue_push(&pqueue, &elts[i]);

}
Ejemplo n.º 12
0
static void
test_pqueue_add_fail_val_oor(void)
{
    struct pqueue q;
    struct pqueue_node nodes[1];
    int rc;
    bwputstr(COM2, "test_pqueue_add_fail_val_oor...");
    pqueue_init(&q, ARRAY_SIZE(nodes), nodes);
    rc = pqueue_add(&q, 1, 42);
    assert(rc == -1);
    rc = pqueue_add(&q, 2, 42);
    assert(rc == -1);
    bwputstr(COM2, "ok\n");
}
Ejemplo n.º 13
0
/* Main sender function. Taken from the state diagram on slide 6, chapter 5 */
void sender(int window, int timeout) {
	 int base = 1;
	 int nextseqnum = 1;
	 bool allsent = false;
	 PQueue sendQ;
	 pqueue_init(&sendQ, window);

	 while ( !(allsent && pqueue_empty(&sendQ)) ) {
		  int acknum = -1;

		  /* Send new data */
		  if (!allsent && nextseqnum < base + window) {
			   Packet* packet = add_packet(&sendQ, nextseqnum);
			   if (packet == NULL) {
					allsent = true;
			   } else {
					send_packet(packet);
					if (base == nextseqnum)
						 start_timer(timeout);
					nextseqnum++;
			   }
		  }
		  
		  /* Attempt to receive an ACK. */
		  acknum = get_ack(0);
		  if (acknum > 0) {
			   base = acknum + 1;
			   if (base == nextseqnum)
					stop_timer();
			   else
					start_timer(timeout);
		  }

		  /* Clean up the queue */
		  while (!pqueue_empty(&sendQ) && pqueue_head(&sendQ)->seqn < base) {
			   pqueue_pop(&sendQ);
		  }
		  
		  /* Handle timeouts */
		  if (cnt_active && cnt_time >= cnt_timeout) {
			   start_timer(cnt_timeout);
			   pqueue_map(&sendQ, &send_packet);
		  }
		  pqueue_debug_print(&sendQ);
	 }
	 
	 pqueue_destroy(&sendQ);
}
Ejemplo n.º 14
0
static void
test_pqueue_add_fail_duplicate1(void)
{
    struct pqueue q;
    struct pqueue_node nodes[2];
    int rc;
    bwputstr(COM2, "test_pqueue_add_fail_duplicate1...");
    pqueue_init(&q, ARRAY_SIZE(nodes), nodes);
    rc = pqueue_add(&q, 0, 42);
    assert(rc == 0);
    rc = pqueue_add(&q, 1, 3);
    assert(rc == 0);
    rc = pqueue_add(&q, 1, 55);
    assert(rc == -2);
    bwputstr(COM2, "ok\n");
}
Ejemplo n.º 15
0
static void
test_pqueue_add_peekmin(void)
{
    struct pqueue q;
    struct pqueue_node nodes[1];
    struct pqueue_entry *min;
    int rc;
    bwputstr(COM2, "test_pqueue_add_peekmin...");
    pqueue_init(&q, ARRAY_SIZE(nodes), nodes);
    rc = pqueue_add(&q, 0, 42);
    assert(rc == 0);
    min = pqueue_peekmin(&q);
    assert(min != NULL);
    assert(min->key == 42);
    assert(min->val ==  0);
    bwputstr(COM2, "ok\n");
}
Ejemplo n.º 16
0
static void
test_pqueue_add2_popmin2_peekmin(void)
{
    struct pqueue q;
    struct pqueue_node nodes[2];
    struct pqueue_entry *min;
    int rc;
    bwputstr(COM2, "test_pqueue_add2_popmin2_peekmin...");
    pqueue_init(&q, ARRAY_SIZE(nodes), nodes);
    rc = pqueue_add(&q, 0, 1);
    assert(rc == 0);
    rc = pqueue_add(&q, 1, 0);
    assert(rc == 0);
    pqueue_popmin(&q);
    pqueue_popmin(&q);
    min = pqueue_peekmin(&q);
    assert(min == NULL);
    bwputstr(COM2, "ok\n");
}
Ejemplo n.º 17
0
int setup(){
	if((pq = (PriorityQueue *)malloc(sizeof(PriorityQueue))) == NULL){
		return -1;
	}
	pqueue_init(pq, NULL, compare);

	for(int i=0; i<10; i++){
		if((u[i] = (UserInfo *)malloc(sizeof(UserInfo))) == NULL){
			free(pq);
			for(int j=i-1; j>=0; j--){
				free(u[j]);
				return -1;
			}
		}
		u[i]->seq = i;
		sprintf(u[i]->username, "%d-item", i);
	}
	return 0;
}
Ejemplo n.º 18
0
void
pqueue_print(pqueue_t *q, FILE *out, pqueue_print_entry_f print)
{
	pqueue_t *dup;
	void *e;

	dup = pqueue_init(q->size, q->cmppri, q->getpri, set_pri,
	                  q->getpos, set_pos);
	dup->size = q->size;
	dup->avail = q->avail;
	dup->step = q->step;

	memcpy(dup->d, q->d, (q->size * sizeof(void *)));

	while ((e = pqueue_pop(dup))) {
		print(out, e);
	}

	pqueue_free(dup);
}
static void
sweep_line_init (sweep_line_t *sweep)
{
    sweep->head.left = INT_MIN;
    sweep->head.next = &sweep->tail;
    sweep->tail.left = INT_MAX;
    sweep->tail.prev = &sweep->head;
    sweep->insert_cursor = &sweep->tail;

    _cairo_freepool_init (&sweep->coverage.pool, sizeof (struct cell));

    sweep->spans = sweep->spans_stack;
    sweep->size_spans = ARRAY_LENGTH (sweep->spans_stack);

    sweep->coverage.head.prev = NULL;
    sweep->coverage.head.x = INT_MIN;
    sweep->coverage.tail.next = NULL;
    sweep->coverage.tail.x = INT_MAX;

    pqueue_init (&sweep->stop);
}
Ejemplo n.º 20
0
static
int
main0(int argc,
     char *argv[])
{
    int i, j;
    struct rlimit rlb;
    char *arg;
    pthread_t tid;
    pthread_attr_t pab;
    
    
    argv0 = argv[0];

    setlocale(LC_CTYPE, "");

    getrlimit(RLIMIT_NOFILE, &rlb);
    rlb.rlim_cur = rlb.rlim_max;
    setrlimit(RLIMIT_NOFILE, &rlb);

    signal(SIGPIPE, SIG_IGN);

    nworkers = 2;

    pthread_mutex_init(&print_lock, NULL);
    pthread_mutex_init(&aworker_lock, NULL);
    pthread_mutex_init(&matches_lock, NULL);

    for (i = 1; i < argc && argv[i][0] == '-'; i++)
	for (j = 1; j > 0 && argv[i][j]; ++j)
	    switch (argv[i][j])
	    {
	      case '-':
		++i;
		goto EndOptions;
		
	      case 'V':
		print_version(stdout);
		break;

	      case 'd':
		++debug;
		break;

	      case 'i':
		ignore_case = 1;
		break;
		
	      case 'v':
		++verbose;
		break;
		
	      case 'h':
		usage(stdout);
		exit(0);
		
	      case 'l':
		++line_f;
		break;
		
	      case 'L':
		if (argv[i][2])
		    arg = argv[i]+2;
		else
		    arg = argv[++i];
		
		if (!arg || sscanf(arg, "%u", &maxlen) != 1)
		{
		    fprintf(stderr, "%s: Invalid length specification: %s\n",
			    argv[0], arg ? arg : "<null>");
		    exit(1);
		}
		j = -2;
		break;
		
	      case 'n':
		if (argv[i][2])
		    arg = argv[i]+2;
		else
		    arg = argv[++i];
		
		if (!arg || sscanf(arg, "%u", &nworkers) != 1)
		{
		    fprintf(stderr,
			    "%s: Invalid workers specification: %s\n",
			    argv[0], arg ? arg : "<null>");
		    exit(1);
		}
		j = -2;
		break;
		
	      default:
		fprintf(stderr, "%s: unknown command line switch: -%c\n",
			argv[0], argv[i][j]);
		exit(1);
	    }

  EndOptions:

    rstr = (unsigned char *) strdup(argv[i++]);
    rlen = deslash(rstr);
    
    if (bm_init(&bmb, rstr, rlen, ignore_case) < 0)
    {
	fprintf(stderr, "%s: Failed search string setup: %s\n",
		argv[0], rstr);
	exit(1);
    }
    
    max_depth = rlb.rlim_max - nworkers - 16;

    if (debug)
	fprintf(stderr, "max_depth = %d, nworkers = %d\n", max_depth,
		nworkers);
    
    pqueue_init(&pqb, nworkers + 8);

    pthread_attr_init(&pab);
    pthread_attr_setscope(&pab, PTHREAD_SCOPE_SYSTEM);

    aworkers = nworkers;
    
    for (j = 0; j < nworkers; ++j)
	if (pthread_create(&tid, &pab, worker, NULL) != 0)
	{
	    fprintf(stderr, "%s: pthread_create: failed to create worker thread\n",
		    argv[0]);
	    exit(1);
	}

    while (i < argc && do_ftw(argv[i++]) == 0)
	;

    pqueue_close(&pqb);

    if (debug)
	fprintf(stderr, "Waiting for workers to finish...\n");
    
    pthread_mutex_lock(&aworker_lock);
    while (aworkers > 0)
	pthread_cond_wait(&aworker_cv, &aworker_lock);
    pthread_mutex_unlock(&aworker_lock);

    if (debug)
	fprintf(stderr, "n_files = %d, n_matches = %d, n_workers = %d, n_Mbytes = %d\n",
		n_files, n_matches, nworkers,
		(int) (n_bytes / 1000000));

    return n_matches;
}
Ejemplo n.º 21
0
static void test_pqueue_many(void)
{
    struct pqueue q;
    struct pqueue_node nodes[32];
    struct pqueue_entry *min;
    int keys[32] = {
        1, 20, 28, 0, 12, 12, 21, 29, 25, 22, 13, 18, 2, 31, 21, 8,
        13, 10, 9, 2, 21, 20, 14, 14, 14, 21, 20, 31, 18, 13, 3, 24
    };
    bool incl[32];
    int i, j, count, rc;

    for (i = 0; i < 32; i++)
        incl[i] = false;

    bwputstr(COM2, "test_pqueue_many...");
    pqueue_init(&q, 32, nodes);

    count = 0;
    i = 0;
    while (count <= 16 - 2) {
        rc = pqueue_add(&q, i, keys[i]);
        assert(rc == 0);
        incl[i++] = true;
        rc = pqueue_add(&q, i, keys[i]);
        assert(rc == 0);
        incl[i++] = true;
        min = pqueue_peekmin(&q);
        assert(min != NULL);
        assert(incl[min->val]);
        assert(keys[min->val] == min->key);
        for (j = 0; j < 32; j++)
            assert(!incl[j] || keys[j] >= min->key);
        incl[min->val] = false;
        pqueue_popmin(&q);
        count++;
    }

    while (count > 0) {
        min = pqueue_peekmin(&q);
        assert(min != NULL);
        assert(incl[min->val]);
        assert(keys[min->val] == min->key);
        for (j = 0; j < 32; j++)
            assert(!incl[j] || keys[j] >= min->key);
        incl[min->val] = false;
        pqueue_popmin(&q);
        count--;
        if (count > 0 && count % 2 == 0) {
            for (i = 0; i < 32; i++) {
                if (incl[i])
                    break;
            }
            keys[i] = -i;
            rc = pqueue_decreasekey(&q, i, -i);
            assert(rc == 0);
        }
    }

    min = pqueue_peekmin(&q);
    assert(min == NULL);
    bwputstr(COM2, "ok\n");
}
Ejemplo n.º 22
0
/**
 * Solve given instance of the knapsack problem using a branch and bound
 * approach.
 * TODO: the solution presented below represents a "rough" attempt and is not
 * in anyway optimized.
 * TODO: solution in terms of which items are picked along the optimal path
 * could easily be recovered by associating with each node a bitvector 
 * encoding the decision made along the tree in order to arrive at that
 * particular node (e.g., for the node encoding that we did not take
 * the first item, but took the second and third items, the node's bit vector
 * would be equal to 011) 
 */
static char *
solve_knapsack_instance_bb(int n, int K, Item *items) {

        PQueue *pq;
        Node *u, *v; 
        Item tmp;
        int maxvalue;
        char *sol = malloc(128 * sizeof(char));
        
        pq = pqueue_init(n, node_get_bound);

        v = malloc(sizeof(Item));
        if (!v) allocation_error();

        v->level = -1;
        v->value = 0;
        v->weight = 0;

        pqueue_enqueue(pq, (void *) v); 

        /* While priority queue is not empty ... */
        while (pq->nElements > 1) {

                pqueue_dequeue(pq, (void **) &v, NULL);

                v->bound = bound(n, K, items, v);

                DEBUG_PRINT("maxvalue: %d\t v->bound: %f", maxvalue, v->bound);

                if (v->bound > maxvalue) {

                        /* Set u to be child that includes next item. */
                        /* Better solution: preallocate and dynamically grow
                         * array of Items to be used as nodes in search tree */
                        u = malloc(sizeof(Node));
                        if (!u) allocation_error();

                        u->level = v->level + 1;
                        u->weight = v->weight + items[u->level].weight;
                        u->value = v->value + items[u->level].value;

                        if (u->weight <= K && u->value > maxvalue) 
                                maxvalue = u->value;

                        u->bound = bound(n, K, items, u);

                        if (u->bound > maxvalue)
                                pqueue_enqueue(pq, (void *) u);
                        else free(u);

                        /* Set u to be child that does not include next item */
                        u = malloc(sizeof(Node));
                        if (!u) allocation_error();

                        u->level = v->level + 1;
                        u->weight = v->weight;
                        u->value = v->value;

                        u->bound = bound(n, K, items, u);

                        if (u->bound > maxvalue)
                                pqueue_enqueue(pq, (void *) u);
                        else free(u);

                        free(v);

                }
        }

        pqueue_free(pq);

        sprintf(sol, "%d\n", maxvalue);
        return sol;
}
Ejemplo n.º 23
0
Archivo: a_star.c Proyecto: jabb/libjab
int a_star(int x0, int y0, int x1, int y1, int *map, int w, int h, int *path, int sz)
{
    static int dirs[8][3] = {
        {-1,  0, 10}, { 0, -1, 10}, { 0,  1, 10}, { 1,  0, 10},
        {-1, -1, 14}, {-1,  1, 14}, { 1, -1, 14}, { 1,  1, 14},
    };
    int ret = 1, i, nx, ny;
    struct a_star_node *nodes = NULL;
    struct a_star_node *ntmp = NULL, *head = NULL, *reversed = NULL;
    struct a_star_node *lowest = NULL, *neighbor = NULL;
    struct pqueue open;

    nodes = malloc(sizeof *nodes * w * h);
    if (!nodes) {
        ret = -1;
        goto failure;
    }
    memset(nodes, 0, sizeof *nodes * w * h);

    nodes[y0 * w + x0].x = x0;
    nodes[y0 * w + x0].y = y0;

    pqueue_init(&open, 256);
    pqueue_push_min(&open, &nodes[y0 * w + x0], a_star_node_cmp);

    while (open.length) {
        pqueue_peek(&open, (void **)&lowest);
        pqueue_pop_min(&open, NULL, a_star_node_cmp);
        lowest->closed = 1;

        if (lowest->x == x1 && lowest->y == y1)
            break;

        for (i = 0; i < 8; ++i) {
            nx = lowest->x + dirs[i][0];
            ny = lowest->y + dirs[i][1];
            neighbor = &nodes[ny * w + nx];
            if (nx >= 0 && nx < w && ny >= 0 && ny < h && !map[ny * w + nx] && !neighbor->closed) {
                if (!pqueue_has(&open, neighbor)) {
                    neighbor->x = nx;
                    neighbor->y = ny;
                    neighbor->g = lowest->g + dirs[i][2];
                    neighbor->h = heuristic(nx, ny, x1, y1);
                    pqueue_push_min(&open, neighbor, a_star_node_cmp);
                    neighbor->parent = lowest;
                }
                else if (lowest->g + dirs[i][2] < neighbor->g) {
                    neighbor->g = lowest->g + dirs[i][2];
                    neighbor->parent = lowest;
                }
            }
        }
    }

    if (!nodes[y1 * w + x1].parent) {
        path[0] = -1;
        path[1] = -1;
        ret = 0;
        goto failure;
    }

    for (head = &nodes[y1 * w + x1]; head; ) {
        ntmp = head;
        head = head->parent;
        ntmp->parent = reversed;
        reversed = ntmp;
    }

    for (i = 0; reversed; reversed = reversed->parent) {
        path[i * 2 + 0] = reversed->x;
        path[i * 2 + 1] = reversed->y;
        if (++i >= sz - 1)
            break;
    }
    path[i * 2 + 0] = -1;
    path[i * 2 + 1] = -1;

failure:
    free(nodes);
    pqueue_uninit(&open, NULL);
    return ret;
}
Ejemplo n.º 24
0
static int build_tree(int *freqs, BiTree **tree) {

BiTree             *init,
                   *merge,
                   *left,
                   *right;

PQueue             pqueue;

HuffNode           *data;

int                size,
                   c;

/*****************************************************************************
*                                                                            *
*  Initialize the priority queue of binary trees.                            *
*                                                                            *
*****************************************************************************/

*tree = NULL;

pqueue_init(&pqueue, compare_freq, destroy_tree);

for (c = 0; c <= UCHAR_MAX; c++) {

   if (freqs[c] != 0) {

      /***********************************************************************
      *                                                                      *
      *  Set up a binary tree for the current symbol and its frequency.      *
      *                                                                      *
      ***********************************************************************/

      if ((init = (BiTree *)malloc(sizeof(BiTree))) == NULL) {

         pqueue_destroy(&pqueue);
         return -1;

      }

      bitree_init(init, free);

      if ((data = (HuffNode *)malloc(sizeof(HuffNode))) == NULL) {

         pqueue_destroy(&pqueue);
         return -1;

      }

      data->symbol = c;
      data->freq = freqs[c];

      if (bitree_ins_left(init, NULL, data) != 0) {

         free(data);
         bitree_destroy(init);
         free(init);
         pqueue_destroy(&pqueue);
         return -1;

      }

      /***********************************************************************
      *                                                                      *
      *  Insert the binary tree into the priority queue.                     *
      *                                                                      *
      ***********************************************************************/

      if (pqueue_insert(&pqueue, init) != 0) {

         bitree_destroy(init);
         free(init);
         pqueue_destroy(&pqueue);
         return -1;

      }

   }

}

/*****************************************************************************
*                                                                            *
*  Build a Huffman tree by merging trees in the priority queue.              *
*                                                                            *
*****************************************************************************/

size = pqueue_size(&pqueue);

for (c = 1; c <= size - 1; c++) {

   /**************************************************************************
   *                                                                         *
   *  Allocate storage for the next merged tree.                             *
   *                                                                         *
   **************************************************************************/

   if ((merge = (BiTree *)malloc(sizeof(BiTree))) == NULL) {

      pqueue_destroy(&pqueue);
      return -1;

   }

   /**************************************************************************
   *                                                                         *
   *  Extract the two trees whose root nodes have the smallest frequencies.  *
   *                                                                         *
   **************************************************************************/

   if (pqueue_extract(&pqueue, (void **)&left) != 0) {

      pqueue_destroy(&pqueue);
      free(merge);
      return -1;

   }

   if (pqueue_extract(&pqueue, (void **)&right) != 0) {

      pqueue_destroy(&pqueue);
      free(merge);
      return -1;

   }

   /**************************************************************************
   *                                                                         *
   *  Allocate storage for the data in the root node of the merged tree.     *
   *                                                                         *
   **************************************************************************/

   if ((data = (HuffNode *)malloc(sizeof(HuffNode))) == NULL) {

      pqueue_destroy(&pqueue);
      free(merge);
      return -1;

   }

   memset(data, 0, sizeof(HuffNode));

   /**************************************************************************
   *                                                                         *
   *  Sum the frequencies in the root nodes of the trees being merged.       *
   *                                                                         *
   **************************************************************************/

   data->freq = ((HuffNode *)bitree_data(bitree_root(left)))->freq +
      ((HuffNode *)bitree_data(bitree_root(right)))->freq;

   /**************************************************************************
   *                                                                         *
   *  Merge the two trees.                                                   *
   *                                                                         *
   **************************************************************************/

   if (bitree_merge(merge, left, right, data) != 0) {

      pqueue_destroy(&pqueue);
      free(merge);
      return -1;

   }

   /**************************************************************************
   *                                                                         *
   *  Insert the merged tree into the priority queue and free the others.    *
   *                                                                         *
   **************************************************************************/

   if (pqueue_insert(&pqueue, merge) != 0) {

      pqueue_destroy(&pqueue);
      bitree_destroy(merge);
      free(merge);
      return -1;

   }

   free(left);
   free(right);

}

/*****************************************************************************
*                                                                            *
*  The last tree in the priority queue is the Huffman tree.                  *
*                                                                            *
*****************************************************************************/

if (pqueue_extract(&pqueue, (void **)tree) != 0) {

   pqueue_destroy(&pqueue);
   return -1;

   }

else {

   pqueue_destroy(&pqueue);

}

return 0;

}
Ejemplo n.º 25
0
/*
** Propagate the tag given by tagid to the children of pid.
**
** This routine assumes that tagid is a tag that should be
** propagated and that the tag is already present in pid.
**
** If tagtype is 2 then the tag is being propagated from an
** ancestor node.  If tagtype is 0 it means a propagating tag is
** being blocked.
*/
static void tag_propagate(
  int pid,             /* Propagate the tag to children of this node */
  int tagid,           /* Tag to propagate */
  int tagType,         /* 2 for a propagating tag.  0 for an antitag */
  int origId,          /* Artifact of tag, when tagType==2 */
  const char *zValue,  /* Value of the tag.  Might be NULL */
  double mtime         /* Timestamp on the tag */
){
  PQueue queue;        /* Queue of check-ins to be tagged */
  Stmt s;              /* Query the children of :pid to which to propagate */
  Stmt ins;            /* INSERT INTO tagxref */
  Stmt eventupdate;    /* UPDATE event */

  assert( tagType==0 || tagType==2 );
  pqueue_init(&queue);
  pqueue_insert(&queue, pid, 0.0, 0);

  /* Query for children of :pid to which to propagate the tag.
  ** Three returns:  (1) rid of the child.  (2) timestamp of child.
  ** (3) True to propagate or false to block.
  */
  db_prepare(&s, 
     "SELECT cid, plink.mtime,"
     "       coalesce(srcid=0 AND tagxref.mtime<:mtime, %d) AS doit"
     "  FROM plink LEFT JOIN tagxref ON cid=rid AND tagid=%d"
     " WHERE pid=:pid AND isprim",
     tagType==2, tagid
  );
  db_bind_double(&s, ":mtime", mtime);

  if( tagType==2 ){
    /* Set the propagated tag marker on checkin :rid */
    db_prepare(&ins,
       "REPLACE INTO tagxref(tagid, tagtype, srcid, origid, value, mtime, rid)"
       "VALUES(%d,2,0,%d,%Q,:mtime,:rid)",
       tagid, origId, zValue
    );
    db_bind_double(&ins, ":mtime", mtime);
  }else{
    /* Remove all references to the tag from checkin :rid */
    zValue = 0;
    db_prepare(&ins,
       "DELETE FROM tagxref WHERE tagid=%d AND rid=:rid", tagid
    );
  }
  if( tagid==TAG_BGCOLOR ){
    db_prepare(&eventupdate,
      "UPDATE event SET bgcolor=%Q WHERE objid=:rid", zValue
    );
  }
  while( (pid = pqueue_extract(&queue, 0))!=0 ){
    db_bind_int(&s, ":pid", pid);
    while( db_step(&s)==SQLITE_ROW ){
      int doit = db_column_int(&s, 2);
      if( doit ){
        int cid = db_column_int(&s, 0);
        double mtime = db_column_double(&s, 1);
        pqueue_insert(&queue, cid, mtime, 0);
        db_bind_int(&ins, ":rid", cid);
        db_step(&ins);
        db_reset(&ins);
        if( tagid==TAG_BGCOLOR ){
          db_bind_int(&eventupdate, ":rid", cid);
          db_step(&eventupdate);
          db_reset(&eventupdate);
        }
        if( tagid==TAG_BRANCH ){
          leaf_eventually_check(cid);
        }
      }
    }
    db_reset(&s);
  }
  pqueue_clear(&queue);
  db_finalize(&ins);
  db_finalize(&s);
  if( tagid==TAG_BGCOLOR ){
    db_finalize(&eventupdate);
  }
}
Ejemplo n.º 26
0
/**
 * Expects a file like:
 **/
void read_data_events(char *mmaped_file) {
   /** Header **/
   FILE *data = open_file(mmaped_file);
   if(!data) {
      printf("#Warning: data file %s not found\n", mmaped_file);
      return;
   }

   if(!data_events)
      data_events = pqueue_init(10, cmp_pri, get_pri, set_pri, get_pos, set_pos);

   rbtree metadata = rbtree_create();

   char line[512];
   struct data_ev *event;
   int nb_lines = 0;
   uint64_t type;


   while(fgets(line, sizeof(line), data)) {
      nb_lines++;
      event = malloc(sizeof(*event));

      if(sscanf(line, "%lu %lu %lu %lu %d %u", &event->rdt, &event->malloc.begin, &event->malloc.end, &type, &event->cpu, &event->tid) != 6) {
         goto test_info;
      }
      if(type == 0) {               // free
         event->type = FREE;
      } else if(type == 2) {        // munmap
         event->type = FREE;        //munmap is not handled correctly yet => fake free
      } else {                      // malloc / mmap
         event->type = MALLOC;
         event->malloc.end = event->malloc.begin + event->malloc.end;
         if(type == 1) {
            char * val = rbtree_lookup(metadata, (void*)event->rdt, pointer_cmp);
            if(val)
               event->malloc.info = val;
            else
               asprintf(&event->malloc.info, "datasize%lu-%d", event->malloc.end - event->malloc.begin, nb_lines);
         } else {
            /*#define MAP_SHARED    0x01 
            #define MAP_PRIVATE     0x02*/
            if(event->malloc.end - event->malloc.begin == 8392704) { /* All stacks seem to be of that size */
               asprintf(&event->malloc.info, "thread-stack-%d", nb_lines);
            } else if(type & 0x01) {
               asprintf(&event->malloc.info, "mmap-shared%lu-%d", event->malloc.end - event->malloc.begin, nb_lines);
            } else if(type & 0x02) {
               asprintf(&event->malloc.info, "mmap-priv%lu-%d", event->malloc.end - event->malloc.begin, nb_lines);
            } else {
               asprintf(&event->malloc.info, "mmap-??%lu-%d", event->malloc.end - event->malloc.begin, nb_lines);
            }
         }
      }


      pqueue_insert(data_events, event);
      total_data_samples++;
      continue;

test_info:;
      uint64_t time, loc;
      int read;
      if(sscanf(line, "#%lu 0x%lx %n\n", &time, &loc, &read) != 2) {
         //printf("fail %s %d\n", line, read);
         goto fail;
      }
      char *met_value = strdup(line + read);
      int met_len = strlen(met_value)-1;
      if(met_len < 5) // malloc probably not correctly resolved
         asprintf(&met_value, "%lu", time);
      else
         met_value[met_len] = '\0';
      rbtree_insert(metadata, (void*)time, met_value, pointer_cmp);

fail:
      //printf("#Unrecognized line: %s", line);
      free(event);
      continue;
   }

   if(!active_data)
      active_data = rbtree_create();

   if(verbose)
      printf("#All data events added successfully ; now processing samples\n");
}
Ejemplo n.º 27
0
int main(int argc, char **argv) {

PQueue             pqueue;

void               *data;

int                intval[30],
                   i;

/*****************************************************************************
*                                                                            *
*  Initialize the priority queue.                                            *
*                                                                            *
*****************************************************************************/

pqueue_init(&pqueue, compare_int, NULL);

/*****************************************************************************
*                                                                            *
*  Perform some priority queue operations.                                   *
*                                                                            *
*****************************************************************************/

i = 0;

intval[i] = 5;
fprintf(stdout, "Inserting %03d\n", intval[i]);
if (pqueue_insert(&pqueue, &intval[i]) != 0)
   return 1;
print_pqueue(&pqueue);
i++;

intval[i] = 10;
fprintf(stdout, "Inserting %03d\n", intval[i]);
if (pqueue_insert(&pqueue, &intval[i]) != 0)
   return 1;
print_pqueue(&pqueue);
i++;

intval[i] = 20;
fprintf(stdout, "Inserting %03d\n", intval[i]);
if (pqueue_insert(&pqueue, &intval[i]) != 0)
   return 1;
print_pqueue(&pqueue);
i++;

intval[i] = 1;
fprintf(stdout, "Inserting %03d\n", intval[i]);
if (pqueue_insert(&pqueue, &intval[i]) != 0)
   return 1;
print_pqueue(&pqueue);
i++;

intval[i] = 25;
fprintf(stdout, "Inserting %03d\n", intval[i]);
if (pqueue_insert(&pqueue, &intval[i]) != 0)
   return 1;
print_pqueue(&pqueue);
i++;

intval[i] = 22;
fprintf(stdout, "Inserting %03d\n", intval[i]);
if (pqueue_insert(&pqueue, &intval[i]) != 0)
   return 1;
print_pqueue(&pqueue);
i++;

intval[i] = 12;
fprintf(stdout, "Inserting %03d\n", intval[i]);
if (pqueue_insert(&pqueue, &intval[i]) != 0)
   return 1;
print_pqueue(&pqueue);
i++;

while (pqueue_size(&pqueue) > 0) {

   fprintf(stdout, "Peeking at the highest priority element..Value=%03d\n",
      *(int *)pqueue_peek(&pqueue));
   if (pqueue_extract(&pqueue, (void **)&data) != 0)
      return 1;
   fprintf(stdout, "Extracting %03d\n", *(int *)data);
   print_pqueue(&pqueue);

}

/*****************************************************************************
*                                                                            *
*  Destroy the priority queue.                                               *
*                                                                            *
*****************************************************************************/

fprintf(stdout, "Destroying the pqueue\n");
pqueue_destroy(&pqueue);

return 0;

}