Esempio n. 1
0
void k_way_sort(data_t *begin, data_t *end, size_t k, less_t &less) {
	//data_t **heap = new data_t[k];
	data_t **heap;
	heap = new data_t*[k];
	for(size_t i = 0; i < k; ++i) {
		heap_insert(heap, i, (begin + i), less);
	}
	
	data_t *iter = begin;
	data_t *next_mas = begin + 1;
	size_t heap_size = k;
	size_t n = std::distance(begin, end);
	*begin = heap_pop(heap, heap_size, less, &iter);
	for(size_t i = 1; i < n; ++i) {
		begin++;
		iter += k;
		if((iter) >= end) {
			// надо что-то делать
			// heap_rebuild();
			// --heap_size
			--heap_size;
			iter = next_mas + k;
			++next_mas;
		}
		heap_insert(heap, heap_size, iter, less);
		*begin = heap_pop(heap, heap_size, less, &iter);
	}
	
	/*
	for(size_t i = 0; i < k; ++i) {
		printf("%d ", *(heap[i]));
	}
	*/
} 
Esempio n. 2
0
int main() {
    heap_node* n[5];

    heap *ph = heap_new();
    n[4] = heap_insert(ph, 4);
    n[1] = heap_insert(ph, 1);
    n[0] = heap_insert(ph, 0);
    n[3] = heap_insert(ph, 3);
    n[2] = heap_insert(ph, 2);

    int i;
    for(i=0; i<5; i++) {
        n[i]->value.v_in_mst = -i;
        n[i]->value.v_not_in_mst = i;
    }

    heap_decrease_key(ph, n[3], -1);

    for(i=0; i<5; i++) {
        int v_not_in_mst = heap_min(ph);
        heap_value* val = &n[v_not_in_mst]->value;
        printf("%d %d %f\n", val->v_in_mst, v_not_in_mst, val->weight);
        heap_delete_min(ph);
    }

    return 0;
}
void new_characters(heap_t *h, cell_t *cell_arr,
		    character **c_arr, room_t *room_arr,
		    int t_char, int num_room)
{
  int i;

  for(i = 1; i < t_char; i++)
    {
      delete (character *)(*(c_arr +i));
    }

  heap_delete(h);
  
  heap_init(h, character_cmp, 0);

  ((pc *)(*c_arr))->place_pc(cell_arr, room_arr, num_room);

  heap_insert(h, *(c_arr + 0));

  for(i = 1; i < t_char; i++)
    {
      *(c_arr + i) = new npc(cell_arr, room_arr, num_room, i); 

      heap_insert(h, *(c_arr + i));
    }
}
int search(struct arg_struct *arg) {
  // printf("# Thread working: %u\n", (int)pthread_self());
  int n = arg->topic;
  int start = arg->startidx;
  int end = arg->endidx;
  heap* h = arg->h;
  heap_create(h,0,NULL);

  int i=0, j=0;
  int base = arg->base;
  float score;
  int t;
  float* min_key;
  int* min_val;

  for (i=start; i<end; i++) {
    if (tweetids[i] > topics2011_time[n]) {
      base += doclengths[i];
      continue;
    }
    score = 0;
    int tf[topics2011[n][1]];
    memset(tf,0,sizeof(tf));
    for (j=0; j<doclengths[i]; j++) {
      for (t=2; t<2+topics2011[n][1]; t++) {
        if (collection_pos[base+j] == topics2011[n][t]) {
          tf[t - 2] ++;
        }
      }
    }
    for (t = 0; t < topics2011[n][1]; t++) {
      if (tf[t] > 0) {
        score += log(1 + tf[t]/(MU * (cf[topics2011[n][t+2]] + 1) / (TOTAL_TERMS + 1))) + log(MU / (doclengths[i] + MU));
      }
    }

    if (score > 0) {
      int size = heap_size(h);

      if ( size < TOP_K ) {
        int *docid = malloc(sizeof(int)); *docid = i;
        float *scorez = malloc(sizeof(float)); *scorez = score;
        heap_insert(h, scorez, docid);
      } else {
        heap_min(h, (void**)&min_key, (void**)&min_val);

        if (score > *min_key) {
          heap_delmin(h, (void**)&min_key, (void**)&min_val);

          int *docid = malloc(sizeof(int)); *docid = i;
          float *scorez = malloc(sizeof(float)); *scorez = score;
          heap_insert(h, scorez, docid);
        }
      }
    }

    base += doclengths[i];
  }
  return 0;
}
Esempio n. 5
0
static void simple_heap_test() {
  printf("Simple Heap\n");

  heap hp;
  heap_node mem[64];
  init_heap(&hp, mem, 64);

  char a = 'a', b = 'b', c = 'c', d = 'd';
  heap_insert(&hp, 1, &b);
  heap_insert(&hp, 100, &d);
  heap_insert(&hp, 0, &a);
  heap_insert(&hp, 5, &c);

  char ret = *(char*) heap_min_value(&hp);
  assert_equals(ret, 'a', "Simple Heap Min 1");

  ret = *(char*) heap_delete_min(&hp);
  assert_equals(ret, 'a', "Simple Heap Delete 1");

  ret = *(char*) heap_min_value(&hp);
  assert_equals(ret, 'b', "Simple Heap Min 2");

  ret = *(char*) heap_delete_min(&hp);
  assert_equals(ret, 'b', "Simple Heap Delete 2");

  ret = *(char*) heap_delete_min(&hp);
  assert_equals(ret, 'c', "Simple Heap Delete 3");

  ret = *(char*) heap_delete_min(&hp);
  assert_equals(ret, 'd', "Simple Heap Delete 4");
}
Esempio n. 6
0
void *match_thread(void *thread_args) {
    long i;
    float score;
    heap_t *heap = NULL;
    thread_args_t *args = (thread_args_t *)thread_args;

    if (args->limit) {
        // Reserve one extra slot so that we can do an insert-then-extract even
        // when "full" (effectively allows use of min-heap to maintain a
        // top-"limit" list of items).
        heap = heap_new(args->limit + 1, cmp_score);
    }

    for (
        i = args->thread_index;
        i < args->path_count;
        i += args->thread_count
    ) {
        args->matches[i].path = RARRAY_PTR(args->haystacks)[i];
        if (args->needle_bitmask == UNSET_BITMASK) {
            args->matches[i].bitmask = UNSET_BITMASK;
        }
        if (!NIL_P(args->last_needle) && args->matches[i].score == 0.0) {
            // Skip over this candidate because it didn't match last
            // time and it can't match this time either.
            continue;
        }
        args->matches[i].score = calculate_match(
            args->matches[i].path,
            args->needle,
            args->case_sensitive,
            args->always_show_dot_files,
            args->never_show_dot_files,
            args->recurse,
            args->needle_bitmask,
            &args->matches[i].bitmask
        );
        if (args->matches[i].score == 0.0) {
            continue;
        }
        if (heap) {
            if (heap->count == args->limit) {
                score = ((match_t *)HEAP_PEEK(heap))->score;
                if (args->matches[i].score >= score) {
                    heap_insert(heap, &args->matches[i]);
                    (void)heap_extract(heap);
                }
            } else {
                heap_insert(heap, &args->matches[i]);
            }
        }
    }

    return heap;
}
Esempio n. 7
0
int main(){
	int a[10] = {5,6,1,2,3,8,7,11,10,20},i=0;
	struct heap heap;
	HEAP_INIT(&heap,12);
	heap_build(&heap,a,10);
	heap_insert(&heap,4);
	heap_insert(&heap,0);
	for(i=0;i<12;i++){
		printf("%d ",heap.heap_arr[i]);
	}
}
Esempio n. 8
0
static int
wf2qp_enqueue(struct dn_sch_inst *_si, struct dn_queue *q, struct mbuf *m)
{
    struct dn_fsk *fs = q->fs;
    struct wf2qp_si *si = (struct wf2qp_si *)(_si + 1);
    struct wf2qp_queue *alg_fq;
    uint64_t len = m->m_pkthdr.len;

    if (m != q->mq.head) {
	if (dn_enqueue(q, m, 0)) /* packet was dropped */
	    return 1;
	if (m != q->mq.head)	/* queue was already busy */
	    return 0;
    }

    /* If reach this point, queue q was idle */
    alg_fq = (struct wf2qp_queue *)q;

    if (DN_KEY_LT(alg_fq->F, alg_fq->S)) {
        /* F<S means timestamps are invalid ->brand new queue. */
        alg_fq->S = si->V;		/* init start time */
        si->wsum += fs->fs.par[0];	/* add weight of new queue. */
	si->inv_wsum = ONE_FP/si->wsum;
    } else { /* if it was idle then it was in the idle heap */
        heap_extract(&si->idle_heap, q);
        alg_fq->S = MAX64(alg_fq->F, si->V);	/* compute new S */
    }
    alg_fq->F = alg_fq->S + len * alg_fq->inv_w;

    /* if nothing is backlogged, make sure this flow is eligible */
    if (si->ne_heap.elements == 0 && si->sch_heap.elements == 0)
        si->V = MAX64(alg_fq->S, si->V);

    /*
     * Look at eligibility. A flow is not eligibile if S>V (when
     * this happens, it means that there is some other flow already
     * scheduled for the same pipe, so the sch_heap cannot be
     * empty). If the flow is not eligible we just store it in the
     * ne_heap. Otherwise, we store in the sch_heap.
     * Note that for all flows in sch_heap (SCH), S_i <= V,
     * and for all flows in ne_heap (NEH), S_i > V.
     * So when we need to compute max(V, min(S_i)) forall i in
     * SCH+NEH, we only need to look into NEH.
     */
    if (DN_KEY_LT(si->V, alg_fq->S)) {
        /* S>V means flow Not eligible. */
        if (si->sch_heap.elements == 0)
            D("++ ouch! not eligible but empty scheduler!");
        heap_insert(&si->ne_heap, alg_fq->S, q);
    } else {
        heap_insert(&si->sch_heap, alg_fq->F, q);
    }
    return 0;
}
Esempio n. 9
0
int main(int argc, char *argv[])
{
  FILE *fp;
  char *line = NULL;
  size_t len = 0;
  int val, min;
  Heap* Hlow = new_heap();
  Heap* Hhigh = new_heap();
  int sum = 0;

  if(argv[1] == NULL) {
    printf("Please specify a source file\n");
    exit(1);
  }

  if((fp = fopen(argv[1], "rb")) == NULL) {
    printf("Couldn't open file. Whomp whomp.\n");
    exit(1);
  }

  while(getline(&line, &len, fp) != EOF) {
    sscanf(line, "%d", &val);

    if(Hlow->size > 0) {
      peek_min(Hlow, &min, &min);

      if(0-val < min)
        heap_insert(Hhigh, val, val);
      else
        heap_insert(Hlow, 0-val, 0-val);
    }
    else {
      heap_insert(Hlow, 0-val, 0-val);
    }

    /* Equalize size of heaps */
    if(Hhigh->size > Hlow->size) {
      extract_min(Hhigh, &val, &val);
      heap_insert(Hlow, 0-val, 0-val);
    }
    else if(Hlow->size > Hhigh->size+1) {
      extract_min(Hlow, &val, &val);
      heap_insert(Hhigh, 0-val, 0-val);
    }

    peek_min(Hlow, &min, &min);
    /* printf("Min: %d\n", min); */
    sum += (0-min);
  }

  printf("Res: %d\n", sum%10000);

  return 0;
}
Esempio n. 10
0
File: events.c Progetto: ablunk/dmx
void events(int num)
{
  int i;
  event *ev;
  // allocate heap
  HEAP = heap_alloc((heapComparator)event_compare);
  assert(HEAP);
  // allocate event pool
  EVENT_POOL = pool_alloc(EVENT_POOL_SIZE, createEvent, destroyEvent);
  assert(EVENT_POOL);
  // initialize simulation time
  TIME = 0;
  ENDTIME = num;
  // insert final event
  if(pooling)
    ev = (event*)pool_get(EVENT_POOL);
  else
    ev = (event*)malloc(sizeof(event));
  assert(ev);
  ev->time = ENDTIME;
  ev->data = (void *)finish;
  heap_insert(HEAP, ev);
  // insert first event
  if(pooling)
    ev = (event*)pool_get(EVENT_POOL);
  else
    ev = (event*)malloc(sizeof(event));
  assert(ev);
  ev->time = TIME;
  ev->data = (void *)foo;
  heap_insert(HEAP, ev);
  // process num events
  while(heap_size(HEAP)>0)
  {
    ev = heap_deleteFirst(HEAP);
    TIME = ev->time;
    ((void (*)())ev->data)();
    if(pooling)
      pool_put(EVENT_POOL, (poolItem *)ev);
    else
      free(ev);
  }
  ev = heap_deleteFirst(HEAP);
  // free heap
  heap_free(HEAP);
  if(pooling)
    pool_free(EVENT_POOL);
  HEAP = NULL;
  finish();
}
int main()
{

    heap_t *heap;
    node_t node;
    int key;
    
    heap = make_heap();

    freopen("input.txt","r",stdin);
     
    while((scanf("%d",&key))!= EOF){
        heap_insert(heap,key);
    }
    
    printf("after insert :\n");
    print_heap(heap);
 
    heap_extract_min(heap,&node);
    printf("min:%d\n",node.key);
    printf("after one extract min\n");
    print_heap(heap);

    return 0;
}
Esempio n. 12
0
void vithist_prune (vithist_t *vh, dict_t *dict, int32 frm,
		    int32 maxwpf, int32 maxhist, int32 beam)
{
    int32 se, fe, filler_done, th;
    vithist_entry_t *ve;
    heap_t h;
    s3wid_t *wid;
    int32 i;
    
    assert (frm >= 0);
    
    se = vh->frame_start[frm];
    fe = vh->n_entry - 1;
    
    th = vh->bestscore[frm] + beam;
    
    h = heap_new ();
    wid = (s3wid_t *) ckd_calloc (maxwpf+1, sizeof(s3wid_t));
    wid[0] = BAD_S3WID;
    
    for (i = se; i <= fe; i++) {
	ve = vh->entry[VITHIST_ID2BLK(i)] + VITHIST_ID2BLKOFFSET(i);
	heap_insert (h, (void *)ve, -(ve->score));
	ve->valid = 0;
    }
    
    /* Mark invalid entries: beyond maxwpf words and below threshold */
    filler_done = 0;
    while ((heap_pop (h, (void **)(&ve), &i) > 0) && (ve->score >= th) && (maxhist > 0)) {
	if (dict_filler_word (dict, ve->wid)) {
	    /* Major HACK!!  Keep only one best filler word entry per frame */
	    if (filler_done)
		continue;
	    filler_done = 1;
	}
	
	/* Check if this word already valid (e.g., under a different history) */
	for (i = 0; IS_S3WID(wid[i]) && (wid[i] != ve->wid); i++);
	if (NOT_S3WID(wid[i])) {
	    /* New word; keep only if <maxwpf words already entered, even if >= thresh */
	    if (maxwpf > 0) {
		wid[i] = ve->wid;
		wid[i+1] = BAD_S3WID;
		
		--maxwpf;
		--maxhist;
		ve->valid = 1;
	    }
	} else if (! vh->bghist) {
	    --maxhist;
	    ve->valid = 1;
	}
    }
    
    ckd_free ((void *) wid);
    heap_destroy (h);
    
    /* Garbage collect invalid entries */
    vithist_frame_gc (vh, frm);
}
Esempio n. 13
0
File: core.c Progetto: catoc/Comojs
int timer_start (evHandle *handle,
                 uint64_t timeout,
                 uint64_t repeat){
    
    if (_is_active(handle)){
        timer_stop(handle);
    }
    
    evTimer *timer;
    if (!handle->type) {
        timer = malloc(sizeof(*timer));
    } else {
        timer = handle->ev;
    }

    uint64_t clamped_timeout = handle->loop->time + timeout;
    if (clamped_timeout < timeout) assert(0);
    timer->timeout = clamped_timeout;
    timer->repeat = repeat;
    timer->start_id = handle->loop->timer_counter++;
    timer->handle = handle;
    handle->ev = timer;
    handle->type = EV_TIMER;
    heap_insert((struct heap*) &handle->loop->timer_heap,
              (struct heap_node*) &timer->heap_node,
              timer_less_than);
    
    handle_start(handle);
    return 1;
}
Esempio n. 14
0
int sfqdfull_add_item_to_queue(struct generic_queue_item* item)
{
	int dispatched=0;

	if (SFQD_FULL_USE_HEAP_QUEUE==1)
	{

		struct heap_node* hn = malloc(sizeof(struct heap_node));
		heap_node_init(hn, item);
		heap_insert(sfqdfull_packet_cmp, sfqdfull_heap_queue, hn);

	}
	else
	{
		if  (PINT_llist_add_to_tail(
				sfqdfull_llist_queue,
		    item))
		{

			fprintf(stderr,"sfqd_full queue insertion error!\n");
			exit(-1);
		}


	}
	return dispatched;
}
Esempio n. 15
0
/*
 * intorel_receive --- receive one tuple
 */
static void
intorel_receive(TupleTableSlot *slot, DestReceiver *self)
{
	DR_intorel *myState = (DR_intorel *) self;
	HeapTuple	tuple;

	/*
	 * get the heap tuple out of the tuple table slot, making sure we have a
	 * writable copy
	 */
	tuple = ExecMaterializeSlot(slot);

	/*
	 * force assignment of new OID (see comments in ExecInsert)
	 */
	if (myState->rel->rd_rel->relhasoids)
		HeapTupleSetOid(tuple, InvalidOid);

	heap_insert(myState->rel,
				tuple,
				myState->output_cid,
				myState->hi_options,
				myState->bistate);

	/* We know this is a newly created relation, so there are no indexes */
}
Esempio n. 16
0
int uv_timer_start(uv_timer_t* handle,
                   uv_timer_cb cb,
                   uint64_t timeout,
                   uint64_t repeat) {
  uint64_t clamped_timeout;

  if (cb == NULL)
    return UV_EINVAL;

  if (uv__is_active(handle))
    uv_timer_stop(handle);

  clamped_timeout = handle->loop->time + timeout;
  if (clamped_timeout < timeout)
    clamped_timeout = (uint64_t) -1;

  handle->timer_cb = cb;
  handle->timeout = clamped_timeout;
  handle->repeat = repeat;
  /* start_id is the second index to be compared in uv__timer_cmp() */
  handle->start_id = handle->loop->timer_counter++;

  heap_insert(timer_heap(handle->loop),
              (struct heap_node*) &handle->heap_node,
              timer_less_than);
  uv__handle_start(handle);

  return 0;
}
Esempio n. 17
0
int main (void)
{
    int i;
    char outOld;
    char out;
    BOOL allesJut;
    srand (time (NULL));
    heap_init ();

    for (i = 0; i < 10; i++)
    {
        heap_insert ( (26 * (rand () / (RAND_MAX + 1.0))) + 97);
    }

    heap_print ();

    heap_extract_min (&outOld);
    allesJut = heap_extract_min (&out);
    while (allesJut) 
    {
        printf ("\n  %c <= %c\n", outOld, out);
        if (outOld <= out)
        {
            outOld = out;
            allesJut = heap_extract_min (&out);
        }
        else
        {
            printf ("\n\tFUCK\n");
            allesJut = FALSE;
        }
    }

}
Esempio n. 18
0
    vector<pair<int, int>> getSkyline(vector<vector<int>>& buildings) {
        n = 0;
        heap.resize(buildings.size());
        id2heap.resize(buildings.size());

        vector<pair<int, int>> results;
        vector<pair<int, int>> points;

        for (int i = 0; i < buildings.size(); i++) {
            points.push_back(make_pair(buildings[i][0], i+1));
            points.push_back(make_pair(buildings[i][1], -(i+1)));
        }
        Comparator compare(buildings);
        sort(points.begin(), points.end(), compare);

        for (auto& p : points) {
            pair<int, int> res;
            if (p.second > 0) {
                int i = p.second-1;
                heap_insert(buildings[i][2], i);
                res = make_pair(p.first, heap_max());
            } else {
                int i = -p.second-1;
                heap_delete(i);
                res = make_pair(p.first, heap_max());
            }
            if (results.empty() || results.back().second != res.second)
                results.push_back(res);
        }

        return results;
    }
int main(){
	int tam,x,i;
	printf("Tamanho e Incerir\n");
	scanf("%d %d",&tam,&x);
    int v,dis,o;
	DIST d[tam];
	tamanho_vetor = tam;
	//d = (DIST*)malloc(tam*sizeof(DIST));
	o = sizeof(d)/sizeof(DIST);
	printf("ooooooooooooolha ->>>>>> %d\n", o);
	tam = -1;
	for(i=0;i<x;i++){
        printf("indice heap\n");
        scanf("%d",&v);
        printf("distancia heap\n");
        scanf("%d", &dis);
        tam = heap_insert(d,v,dis,tam);
	}
	printf("tamanho final: %d\n",tam);
	for(i=0;i<x;i++){
		printf("indice %d -----> %d\n",d[i].v,d[i].d);
	}


}
Esempio n. 20
0
void heap_cpu()
{
    int a = 0;
    void* p = 0;
    int i = 0;
    int to = 0;
    unsigned int old =  getnowtime();
    struct heap_s* heap = heap_new(100000, sizeof(int), compare_int, swap_int, NULL);
    
    old =  getnowtime();
    printf("开始添加堆元素:%d\n", old);   
    for(; i < 1000000; ++i)
    {
        a = rand() % 10000;
        heap_insert(heap, &a);
    }

    old =  getnowtime();
    printf("添加完毕,开始pop:%d\n", old);  
    while( p =heap_pop(heap))
    {
        to++;
            //int temp = *(int*)p;
            //printf("%d\n", temp);
        ;
    }
    
    old =  getnowtime();
    printf("pop完毕:%d, to:%d\n", old, to);  
}
Esempio n. 21
0
int threadpool_add_task(threadpool_t *pool, 
        void (*func)(void*), void *arg, int priority) {
    int tosignal = 0;
    task_t *tq = (task_t *)calloc(1, sizeof(*tq));
    if (!tq) {
        return -1;
    }

    tq->func = func;
    tq->arg = arg;
    tq->priority = priority;

    Pthread_mutex_lock(&pool->mutex);
    if (pool->threads_idle == 0 && pool->threads_num < pool->threads_max) {
        threadpool_thread_create(pool);
        ++pool->threads_idle;
        ++pool->threads_num;
    }
    tosignal = (pool->task_queue.len == 0)  ? 1 : 0;
    if (heap_insert(&pool->task_queue, tq) != 0) {
        free(tq);
        Pthread_mutex_unlock(&pool->mutex);
        return -1;
    }
    Pthread_mutex_unlock(&pool->mutex);
    if (tosignal) {
        Pthread_cond_broadcast(&pool->cond);
    }
    return 0;
}
int main()
{
	int A[MAXSIZE];
	char choice[10];
        char choice2[10];
	int element;
	int heap_size;
	
	heap_size = 0;

        do {
                scanf("%s", choice);

                switch (choice[0]) {
                        case 'i' : scanf("%d", &element);
                                   heap_insert(A, &heap_size, element);
                                break;
                        case 'e' : scanf("%s", choice2);
                                   printf("%d\n", extract_heap_max(A, &heap_size));
                                break;
			case 'm' : printf("%d\n", heap_max(A, &heap_size));
                                break;
			case 'p' : print_heap(A, &heap_size);
				break;
                        case 'q' : break;
                        default  : printf("Incorrect command!\n");
                                break;
                }
        } while (choice[0] != 'q');

	return 0;
}
Esempio n. 23
0
/**
    After collision the ould collision tree
    with movables for given object still exists,
    as well as information about collisin with
    the object, that are no longer valid.
    This function clears the tree with post-order
    deleting info.
    */
void coll_clear_trash(level_data *level, coll_node *node, coll_node *nil){
    if(node != nil){
        coll_clear_trash(level, node->left, nil);
        coll_clear_trash(level, node->right, nil);

        short int temp = node->key.with;
        node->key.with = node->key.who;
        node->key.who = temp;

        temp = coll_comp(&node->key, level->movable_objects[node->key.who].next_collision);
        coll_delete_node(&level->movable_objects[node->key.who].colls_with_mov, &node->key);
        if(temp == EQUAL){
            //mark dirty
            temp = node->key.who;
            if(node->key.with < node->key.who){
                node->key.who = node->key.with;
                node->key.with = temp;
            }
            coll_insert_node(&level->dirty_tree, &node->key);
            //find new min
            collision_min_for_object(level, temp);
            //push on queue //how to push so that one collision gets on queue only once?
            if(level->movable_objects[node->key.who].next_collision->time >= 0 &&
               level->movable_objects[node->key.who].next_collision->time <= 1){
                heap_insert(&level->collision_queue, level->movable_objects[node->key.who].next_collision);
            }
        }
        free(node);
    }
}
void outputSorted(const Person people[],
        int numPeople,
        int (* compare)(const void *pKey1, const void *pKey2))
{
    Heap heap;
    void *data;
    int i;

    /* Initialize heap */
    heap_init(&heap, compare, NULL);

    /* Add people to heap */
    for (i = 0; i < numPeople; ++i)
        if (heap_insert(&heap, &people[i]) != 0)
            fatalError("Failed to insert person into heap");

    /* Extract and output people from heap */
    while (heap_size(&heap) > 0) {
        if (heap_extract(&heap, &data) != 0)
            fatalError("Failed to extract person from heap");
        outputPerson((const Person *)data);
    }

    /* Destroy heap */
    heap_destroy(&heap);
}
Esempio n. 25
0
static void firewall_rule_delete(scamper_firewall_entry_t *entry)
{
#if defined(HAVE_IPFW)
  int af;

  if(entry->rule->sfw_5tuple_src->type == SCAMPER_ADDR_TYPE_IPV4)
    af = AF_INET;
  else
    af = AF_INET6;

#ifdef WITHOUT_PRIVSEP
  scamper_firewall_ipfw_del(entry->slot, af);
#else
  scamper_privsep_ipfw_del(entry->slot, af);
#endif
#endif

  /* put the rule back into the freeslots heap */
  if(heap_insert(freeslots, entry) == NULL)
    {
      printerror(errno, strerror, __func__,
		 "could not add entry %d", entry->slot);
      firewall_entry_free(entry);
    }

  /* free up the firewall rule associated with the entry */
  firewall_rule_free(entry->rule);
  entry->rule = NULL;

  return;
}
Esempio n. 26
0
static void
heap_purgeDone(RemovalPurgeWalker * walker)
{
    HeapPurgeData *heap_walker = walker->_data;
    RemovalPolicy *policy = walker->_policy;
    HeapPolicyData *heap = policy->_data;
    StoreEntry *entry;
    assert(strcmp(policy->_type, "heap") == 0);
    assert(heap->nwalkers > 0);
    heap->nwalkers -= 1;
    if (heap_walker->min_age > 0) {
	heap->heap->age = heap_walker->min_age;
	debug(81, 3) ("heap_purgeDone: Heap age set to %f\n",
	    (double) heap->heap->age);
    }
    /*
     * Reinsert the locked entries
     */
    while ((entry = linklistShift(&heap_walker->locked_entries))) {
	heap_node *node = heap_insert(heap->heap, entry);
	SET_POLICY_NODE(entry, node);
	storeUnlockObject(entry);
    }
    safe_free(walker->_data);
    cbdataFree(walker);
}
Esempio n. 27
0
void _st_add_sleep_q(_st_thread_t *thread, st_utime_t timeout)
{
  thread->due = _ST_LAST_CLOCK + timeout;
  thread->flags |= _ST_FL_ON_SLEEPQ;
  thread->heap_index = ++_ST_SLEEPQ_SIZE;
  heap_insert(thread);
}
Esempio n. 28
0
static heap_t * test_create (test_input_t * data, heap_t * (*creator)(size_t))
{
  size_t ii, capacity;
  heap_t * heap;
  
  fprintf (stderr, "scanning input data:\n");
  for (ii = 0; data[ii].value; ++ii) {
    fprintf (stderr, "  % 5.2f\t%s\n", data[ii].key, data[ii].value);
  }
  fprintf (stderr, "there seem to be %zu data items\n", ii);
  
  capacity = ii / 2 + 1;
  fprintf (stderr, "creating heap with capacity %zu\n", capacity);
  heap = creator (capacity);
  if ( ! heap) {
    err (EXIT_FAILURE, "maxheap_create");
  }
  
  fprintf (stderr, "inserting data into heap\n");
  for (ii = 0; data[ii].value; ++ii) {
    fprintf (stderr, "  inserting item %zu (% 5.2f\t%s)\n", ii, data[ii].key, data[ii].value);
    heap_insert (heap, data[ii].key, data[ii].value);
    test_dump (heap, "    ");
  }
  
  return heap;
}
Esempio n. 29
0
File: timer.c Progetto: aosm/Heimdal
static void
trigger_jobs(void)
{
    time_t now = time(NULL);

    while (1) {
	struct heim_event_data *e = rk_UNCONST(heap_head(timer_heap));

	if (e != NULL && e->t < now) {
	    heap_remove_head(timer_heap);
	    e->hptr = HEAP_INVALID_PTR;

	    /* if its already running, lets retry 10s from now */
	    if (e->flags & RUNNING) {
		e->t = now + 10;
		heap_insert(timer_heap, e, &e->hptr);
		continue;
	    }
	    e->flags |= RUNNING;

	    _heim_ipc_suspend_timer();

	    dispatch_async(timer_job_q, ^{ 
		    e->callback(e, e->ctx); 
		    dispatch_async(timer_sync_q, ^{
			    e->flags &= ~RUNNING;
			    if (e->running)
				dispatch_semaphore_signal(e->running);

			    _heim_ipc_restart_timer();
			});
		});
Esempio n. 30
0
glist_t vithist_sort (glist_t vithist_list)
{
    heap_t heap;
    gnode_t *gn;
    vithist_t *h;
    glist_t vithist_new;
    int32 ret, score;

    vithist_new = NULL;

    heap = heap_new();
    for (gn = vithist_list; gn; gn = gnode_next(gn)) {
        h = (vithist_t *) gnode_ptr(gn);
        if (heap_insert (heap, (void *) h, h->scr) < 0) {
            E_ERROR("Panic: heap_insert() failed\n");
            return NULL;
        }
    }

    /*
     * Note: The heap returns nodes with ASCENDING values; and glist_add adds new nodes to the
     * HEAD of the list.  So we get a glist in the desired descending score order.
     */
    while ((ret = heap_pop (heap, (void **)(&h), &score)) > 0)
        vithist_new = glist_add_ptr (vithist_new, (void *)h);
    if (ret < 0) {
        E_ERROR("Panic: heap_pop() failed\n");
        return NULL;
    }

    heap_destroy (heap);

    return vithist_new;
}