void test_heap_test_1(void) { char heap_mem[heap_mem_size(16, sizeof(uint32_t))]; struct heap *h = heap_create( heap_mem , sizeof(heap_mem) , sizeof(uint32_t) , u32_leq , u32_cpy ); fprintf(stdout, "# heap_size: %ld\n", heap_size(h)); fprintf(stdout, "# heap_empty: %s\n", heap_empty(h) ? "yes" : "no"); uint32_t vs[] = {9,100,7,2,5,200,1,20,8,8,8,150}; size_t i = 0; for(; i < sizeof(vs)/sizeof(vs[0]); i++ ) { if( !heap_add(h, &vs[i]) ) { break; } } fprintf(stdout, "# heap_empty: %s\n", heap_empty(h) ? "yes" : "no"); while( !heap_empty(h) ) { uint32_t *mp = heap_pop(h); if( !mp ) break; fprintf(stdout, "# %d\n", *mp); } }
static void MY_dequeue(struct run_queue *rq, struct proc_struct *proc) { assert(!heap_empty(heap) && proc->rq == rq); rq->proc_num --; // heap part heap_entry_t elm; if (!heap_empty(heap)) elm = heap_pop(heap); }
// FIXME - we don't cope optimally with the situation where a branch is // created, files deleted, and then the branch tagged (without rtag). We'll // never know that the tag was placed on the branch; instead we'll place the tag // on the trunk. static void branch_graph (database_t * db, tag_t *** tree_order, tag_t *** tree_order_end) { // First, go through each tag, and put it on all the branches. for (tag_t * i = db->tags; i != db->tags_end; ++i) { i->changeset.unready_count = 0; for (version_t ** j = i->tag_files; j != i->tag_files_end; ++j) { if ((*j)->branch) record_branch_tag ((*j)->branch, i); if (*j != (*j)->file->versions && (*j)[-1].implicit_merge && (*j)[-1].used && (*j)[-1].branch) record_branch_tag ((*j)[-1].branch, i); } } // Go through each branch and put record it on the tags. for (tag_t * i = db->tags; i != db->tags_end; ++i) for (branch_tag_t * j = i->tags; j != i->tags_end; ++j) { ARRAY_EXTEND (j->tag->parents); j->tag->parents_end[-1].branch = i; j->tag->parents_end[-1].weight = j->weight; ++j->tag->changeset.unready_count; } // Do a cycle breaking pass of the branches. heap_t heap; heap_init (&heap, offsetof (tag_t, changeset.ready_index), tag_compare); // Release all the tags that are ready right now; also sort the parent // lists. for (tag_t * i = db->tags; i != db->tags_end; ++i) { ARRAY_SORT (i->parents, compare_pb); if (i->changeset.unready_count == 0) { i->is_released = true; heap_insert (&heap, i); } } while (!heap_empty (&heap)) tag_released (&heap, heap_pop (&heap), tree_order, tree_order_end); for (tag_t * i = db->tags; i != db->tags_end; ++i) while (!i->is_released) { break_cycle (&heap, i); while (!heap_empty (&heap)) tag_released (&heap, heap_pop (&heap), tree_order, tree_order_end); } heap_destroy (&heap); }
int main() { struct heap heap; int result = heap_init(&heap, int_compare); assert(result == 0); assert(heap_empty(&heap)); assert(heap_size(&heap) == 0); static const intptr_t VALUES[] = {12, 2955, 7, 99, 51, 1, 691050}; static const intptr_t EXPECTED[] = {1, 7, 12, 51, 99, 2955, 691050}; int count = sizeof(VALUES) / sizeof(VALUES[0]); for (int i = 0; i < count; i++) { result = heap_push(&heap, (void*)VALUES[i]); assert(result == 0); } assert(heap_size(&heap) == count); assert(!heap_empty(&heap)); assert((intptr_t)heap_min(&heap) == (intptr_t)1); assert(heap_size(&heap) == count); for (int i = 0; i < count; i++) { intptr_t value = (intptr_t)heap_pop_min(&heap); assert(value == EXPECTED[i]); } assert(heap_empty(&heap)); assert(heap_size(&heap) == 0); assert(heap_min(&heap) == NULL); assert(heap_pop_min(&heap) == NULL); // Repeat reordered static const intptr_t VALUES2[] = {2955, 12, 691050, 99, 51, 1, 7}; for (int i = 0; i < count; i++) { result = heap_push(&heap, (void*)VALUES2[i]); assert(result == 0); } for (int i = 0; i < count; i++) { intptr_t value = (intptr_t)heap_pop_min(&heap); assert(value == EXPECTED[i]); } assert(heap_empty(&heap)); assert(heap_size(&heap) == 0); assert(heap_min(&heap) == NULL); assert(heap_pop_min(&heap) == NULL); heap_free(&heap); return 0; }
void * heap_remove_min(heap H) { int i, Child; void * MinElement, LastElement; int * elements = (int *) H->Elements; if (heap_empty(H)) { return (void *) elements[ 0 ]; } MinElement = (void *) elements[ 1 ]; LastElement = (void *) elements[ H->Size-- ]; for (i = 1; i * 2 <= H->Size; i = Child) { Child = i * 2; if (Child != H->Size && H->Comparer((void *)elements[ Child + 1 ], (void *)elements[ Child ]) < 0) Child++; if (H->Comparer(LastElement,(void *)elements[ Child ]) > 0) elements[ i ] = elements[ Child ]; else break; } elements[ i ] = (int) LastElement; return MinElement; }
void * heap_get_min(heap H) { int * elements = (int *) H->Elements; if (!heap_empty(H)) return (void *)elements[ 1 ]; Error("Priority Queue is Empty"); return (void *)elements[ 0 ]; }
// Pop a plan location from the queue plan_cell_t *plan_pop(plan_t *plan) { if(heap_empty(plan->heap)) return(NULL); else return(heap_extract_max(plan->heap)); }
void *i_request_memory_block() { U32 *block = NULL; if (!heap_empty(&p_heap)) { block = heap_pop(&p_heap); } return block; }
// called when current proc neeeds reschedule is true static struct proc_struct * MY_pick_next(struct run_queue *rq) { if (heap_empty(heap)) panic("sched_MY.c pick_next: heap is empty!\n"); // heap part heap_entry_t elm = heap_gettop(heap); struct proc_struct *heapNext = (struct proc_struct *)elm.proc; return heapNext; }
heap heap_new(int capacity, higher_priority_fn *prior) { REQUIRES(capacity > 0 && prior != NULL); heap H = malloc(sizeof(struct heap_header)); H->next = 1; H->limit = capacity + 1; H->data = malloc(sizeof(void*) * H->limit); H->prior = prior; ENSURES(is_heap(H) && heap_empty(H)); return H; }
void test_heap_test_4(void) { size_t memsize = heap_mem_size(1, sizeof(struct cw)); fprintf(stderr, "memsize: %ld\n", memsize); char heap_mem[heap_mem_size(1, sizeof(struct cw))]; struct heap *h = heap_create( heap_mem , sizeof(heap_mem) , sizeof(struct cw) , __cw_leq , __cw_cpy ); fprintf(stderr, "heap: %p\n", h); fprintf(stdout, "# heap_size: %ld\n", heap_size(h)); struct cw cats[] = { { 1, 1 } , { 2, 1 } , { 1, 2 } , { 3, 1 } , { 12, 3 } , { 5, 1 } , { 31, 2 } , { 6, 2 } , { 7, 1 } , { 7, 1 } , { 10, 5 } }; fprintf(stdout, "\n"); size_t i = 0; for(; i < sizeof(cats)/sizeof(cats[0]); i++ ) { fprintf(stdout, "# {%d, %d}\n", cats[i].cat, cats[i].weight); if( heap_full(h) ) { struct cw *min = heap_get(h); if( __cw_leq(min, &cats[i]) ) { heap_pop(h); } } heap_add(h, &cats[i]); } fprintf(stdout, "\nheap_items %ld\n", heap_items(h)); fprintf(stdout, "\n"); while( !heap_empty(h) ) { struct cw *c = heap_pop(h); fprintf(stdout, "# {%d, %d}\n", c->cat, c->weight); } }
void heap_free(heap_t* h) { if(h->free_fn) { while(!heap_empty(h)) (*h->free_fn)(heap_extract_max(h)); } free(h->data); free(h->A); free(h); }
/* * heap_rem_elem - Removes an arbitrary element in the heap by finding * its index with linear search and then swapping * and deleting with the bottom-most, right-most element. */ void heap_rem_elem(heap H, elem x) { REQUIRES(is_heap(H) && !heap_empty(H)); int idx = find_elem(H, x); H->next--; if (H->next > 1) { H->data[idx] = H->data[H->next]; sift_down(H, idx); } ENSURES(is_heap(H)); }
void test_heap_test_2(void) { char heap_mem[heap_mem_size(10, sizeof(uint32_t))]; struct heap *h = heap_create( heap_mem , sizeof(heap_mem) , sizeof(uint32_t) , u32_leq , u32_cpy ); fprintf(stdout, "# heap_size: %ld\n", heap_size(h)); size_t N = 3000; size_t n = 0; for(n = N; n; n-- ) { __test_head_add_gt(h, n); } fprintf(stdout, "\n"); while( !heap_empty(h) ) { uint32_t *mp = heap_pop(h); if( !mp ) break; fprintf(stdout, "# %d\n", *mp); } for(n = 0; n <= N; n++ ) { __test_head_add_gt(h, n); } fprintf(stdout, "\n"); while( !heap_empty(h) ) { uint32_t *mp = heap_pop(h); if( !mp ) break; fprintf(stdout, "# %d\n", *mp); } }
elem heap_rem(heap H) { REQUIRES(is_heap(H) && !heap_empty(H)); elem min = H->data[1]; H->next--; if (H->next > 1) { H->data[1] = H->data[H->next]; sift_down(H, 1); } ENSURES(is_heap(H)); return min; }
void *k_request_memory_block() { U32 *block = NULL; while (gp_current_process->memory_block == NULL && heap_empty(&p_heap)) { // Block current process until a block is free gp_current_process->state = BLOCK; k_release_processor(); } if (gp_current_process->memory_block != NULL) { // Unblocked by release_memory_block block = gp_current_process->memory_block; gp_current_process->memory_block = NULL; } else { // Memory available in heap block = heap_pop(&p_heap); } return block; }
int support_time_left() { suptimer_t *tmr; uint64_t now; if (heap_empty(&timers)) return -1; tmr = timers_top(); now = support_get_sys_timestamp(); if (now > tmr->target) return 0; return tmr->target - now; }
void support_handle_timers() { uint64_t now = support_get_sys_timestamp(); suptimer_t *tmr; while (!heap_empty(&timers)) { tmr = timers_top(); if (tmr->target > now) break; heap_pop(&timers); tmr->target = IMPOSSIBLE_FUTURE; timer_expired(tmr); } }
void main_loop(void) { int n; struct timer *timer; int delay; while (num_pollfds > 1 || heap_len(timers) > 1 || pollfds[0].events & POLLOUT) { if (heap_empty(timers)) { timer = NULL; delay = -1; } else { timer = heap_peek(timers); delay = (timer->time - get_now()) * 1000; } if (timer && delay <= 0) n = 0; else n = poll(pollfds, num_pollfds, delay); if (!n) { timer = heap_extract_min(timers); timer->func(timer->data); free(timer); goto cont; } for (int i = 0; i < num_pollfds && n; i++) { if (pollfds[i].revents) { event_handlers[i]->func(event_handlers[i]->data); n--; /* We may have just deleted this id. * Try it again in case it's a new * one. */ i--; } } cont: maybe_dequeue(); } }
/*--------------------------------------------------------------------------------------* * Does an in-place heap sort of the array. * * INPUT: The array to be sorted, the size of the array, and a function to order the * * elements. The array stores pointers to the elements that must be sorted. * *--------------------------------------------------------------------------------------*/ void heapSort(void ** data, int size, int (*compare)(void *, void *)) { int i; normalCompare = compare; struct heap heap; //this is allowed because the index 0 of the heap is never accessed and this effectively makes the heap the data array heap.data = data - 1; heap.capacity = size; heap.endptr = size; heap.compare = reverseCompare; /*enforce the heap constraint (each parent is as large or larger than both its children) by calling bubble down on all nodes that would have children */ for(i = heap.capacity / 2; i > 0; i--){ bubbledown(&heap, i); } /* takes the value at the top of the heap and puts it last in the data */ while(!heap_empty(&heap)){ data[heap.endptr] = heap_remove_min(&heap); } }
int top_main (int argc, char ** argv) { char c; heap h = heap_init(1024, (void *) proc_comparer); do { int allow_zombies = 0; if (argc > 1 && !strcmp(argv[1], "zombies")) { allow_zombies = 1; } int len = 0; int i = 0; int active_pids[PROCESS_MAX]; int active_pids_ticks[PROCESS_MAX]; int active_pids_n = 0; for(; i < PROCESS_MAX; ++i) { active_pids[i] = -1; active_pids_ticks[i] = 0; } int tick_history[PROCESS_HISTORY_SIZE]; int * _pticks = pticks(); i = 0; for(; i < PROCESS_HISTORY_SIZE; i++) { if(_pticks[i] == -1) { break; } tick_history[i] = _pticks[i]; } len = i; i = 0; int zombs = 0; for(; i < len; ++i) { int pid = tick_history[i]; int _pid_index = -1, j = 0; for(; j < active_pids_n; j++) { if(active_pids[j] == pid) { _pid_index = j; break; } } if(_pid_index == -1) { _pid_index = active_pids_n; active_pids[_pid_index] = pid; active_pids_n++; } if (pstatus(pid) != PROCESS_ZOMBIE) { active_pids_ticks[_pid_index]++; } else { zombs++; } } if (!allow_zombies) { len -= zombs; } i = 0; int printed = 0; for(; i < PROCESS_MAX; ++i) { int pid = pgetpid_at(i); if (pid != -1){ int j = -1; for(; j < active_pids_n; j++) { if(active_pids[j] == pid) { break; } } int ticks = ( j == -1 ) ? 0 : active_pids_ticks[j]; top_data * data = (top_data *) malloc(sizeof(top_data)); data->ticks = ticks; data->pid = pid; heap_insert(data, h); } } i = 0; while(!heap_empty(h)) { top_data * data = heap_remove_min(h); if(0) { break; } else { i++; int pid = data->pid; int ticks = data->ticks; char * _pname = pname(pid); char * status = NULL; int stat = pstatus(pid); switch(stat){ case PROCESS_READY: status = "READY"; break; case PROCESS_BLOCKED: status = "BLOCKED"; break; case PROCESS_ZOMBIE: status = "ZOMBIE "; break; case PROCESS_RUNNING: status = "RUNNING"; break; default: status = "UNKNOWN"; } int priority = ppriority(pid); len = (!len) ? 1 : len; if (stat != PROCESS_ZOMBIE || (stat == PROCESS_ZOMBIE && allow_zombies) ) { printed++; printf("PID: %d \t NAME: %s \t CPU:%% %d \t STATUS: %s \t PRIORITY: %d\n", pid, _pname, (100 * ticks) / len, status, priority); } } } printf("--------------------------------------------------------------------------------\n"); sleep(1024); } while(1); return 0; }
struct astar_node *astar_search(struct astar_search_info *info) { struct astar_node *node; int row; int col; int cost = 0; int goodness = 0; astar_search_init(); info->heuristic(info, &goodness, &cost, info->x0, info->y0); node = astar_node_create(info->x0, info->y0, cost, goodness, NULL, COORD_TO_INDEX(info->x0, info->y0, info->width)); astar_schedule(node); while (!heap_empty(schedule)) { //astar_dump_schedule(); node = astar_schedule_extract(); /* Check if this node is the target location */ if ((info->flags & ASTAR_HORZ || node->x == info->x1) && (info->flags & ASTAR_VERT || node->y == info->y1)) { /* Reverse the path to get a pointer to the start */ node = astar_path_reverse(node); /* Remove the nodes in the path from the tree so that * we don't free them with the rest */ astar_explored_remove(node); goto done; } /* Check if this node is at max depth */ if (node->depth == MAX_DEPTH || (info->limit_depth && node->depth == info->max_depth)) { continue; } /* Check the four non-diagonal neighbors of this node */ for (row = 0, info->y0 = node->y - 1; row < 3; row++, info->y0++) { /* Wrap y-coord if applicable */ if (info->wraps) info->y0 = ((info->y0 + info->height) % info->height); for (col = 0, info->x0 = node->x - 1; col < 3; col++, info->x0++) { #if (CONFIG_NEIGHBORS==4) /* skip diagonals and center */ if (((row * 3 + col) % 2) == 0) { continue; } #elif (CONFIG_NEIGHBORS==8) /* skip center */ if ((row == col) && (row == 1)) { continue; } #else # error CONFIG_NEIGHBORS undefined or has bad value #endif /* Wrap x-coord if applicable */ if (info->wraps) info->x0 = ((info->x0 + info->width) % info->width); /* Skip this neighbor if it's not a valid * location (impassable, off-map, etc) */ if (!info->is_valid_location(info->context, node->x, node->y, info->x0, info->y0)) continue; astar_schedule_neighbor(node, info); } } } node = 0; done: astar_cleanup(); return node; }
void create_changesets (database_t * db) { size_t total_versions = 0; for (file_t * i = db->files; i != db->files_end; ++i) total_versions += i->versions_end - i->versions; if (total_versions == 0) return; version_t ** version_list = ARRAY_ALLOC (version_t *, total_versions); version_t ** vp = version_list; for (file_t * i = db->files; i != db->files_end; ++i) for (version_t * j = i->versions; j != i->versions_end; ++j) *vp++ = j; assert (vp == version_list + total_versions); qsort (version_list, total_versions, sizeof (version_t *), version_compare_qsort); changeset_t * current = database_new_changeset (db); ARRAY_APPEND (current->versions, version_list[0]); version_list[0]->commit = current; current->time = version_list[0]->time; current->type = ct_commit; for (size_t i = 1; i < total_versions; ++i) { version_t * next = version_list[i]; if (!strings_match (*current->versions, next) || next->time - current->time > fuzz_span || next->time - current->versions_end[-1]->time > fuzz_gap) { ARRAY_TRIM (current->versions); current = database_new_changeset (db); current->time = next->time; current->type = ct_commit; } ARRAY_APPEND (current->versions, version_list[i]); version_list[i]->commit = current; } ARRAY_TRIM (current->versions); free (version_list); // Do a pass through the changesets; this breaks any cycles. heap_t ready_versions; heap_init (&ready_versions, offsetof (version_t, ready_index), version_compare_heap); prepare_for_emission (db, &ready_versions); ssize_t emitted_changesets = 0; changeset_t * changeset; while ((changeset = next_changeset_split (db, &ready_versions))) { changeset_emitted (db, &ready_versions, changeset); ++emitted_changesets; } // Sort the changeset version lists by file. for (changeset_t ** i = db->changesets; i != db->changesets_end; ++i) ARRAY_SORT ((*i)->versions, compare_version_by_file); assert (heap_empty (&ready_versions)); assert (heap_empty (&db->ready_changesets)); assert (emitted_changesets == db->changesets_end - db->changesets); heap_destroy (&ready_versions); }
struct generic_queue_item * sfqdfull_dequeue(struct dequeue_reason r) { //int last_io_type = r.complete_size; struct generic_queue_item * next;//for heap and list //free up current item struct generic_queue_item * next_item = NULL; //for actual list item removal struct sfqdfull_queue_item *next_queue_item; int found=0; next_retry: if (SFQD_FULL_USE_HEAP_QUEUE==1 && !heap_empty(sfqdfull_heap_queue)) { struct heap_node * hn = heap_take(sfqd_packet_cmp, sfqdfull_heap_queue); next_item = heap_node_value(hn); next_queue_item = (struct sfqdfull_queue_item *)(next_item->embedded_queue_item); found=1; } char bptr[20]; struct timeval tv; time_t tp; gettimeofday(&tv, 0); tp = tv.tv_sec; strftime(bptr, 10, "[%H:%M:%S", localtime(&tp)); sprintf(bptr+9, ".%06ld]", (long)tv.tv_usec); //fprintf(stderr,"%s %s, finished %i complete recv %i, completefwd %i\n", bptr, log_prefix, finished[0], completerecv[0], completefwd[0]); if (SFQD_FULL_USE_HEAP_QUEUE==0) { /*if (sfqdfull_sorted==0) { sfqdfull_llist_queue = PINT_llist_sort(sfqdfull_llist_queue,list_sfqd_sort_comp); sfqdfull_sorted=1; }*/ int i; fprintf(stderr,"%s %s ",bptr,log_prefix); for (i=0;i<num_apps;i++) { fprintf(stderr,"app%i:%i,", i, sfqdfull_list_queue_count[i]); } fprintf(stderr,"\n"); next = (struct generic_queue_item *)PINT_llist_head(sfqdfull_llist_queue); if (next!=NULL) { next_item = (struct generic_queue_item *)PINT_llist_rem(sfqdfull_llist_queue, (void*)next->item_id, list_req_comp); } if (next_item!=NULL) { next_queue_item = (struct sfqdfull_queue_item *)(next_item->embedded_queue_item); sfqdfull_list_queue_count[next_queue_item->app_index]--; found=1; fprintf(stderr," meta dispatching \n"); int app_index=next_queue_item->app_index; if (next_queue_item->app_index==1 && sfqdfull_list_queue_count[0]==0){ fprintf(stderr,"%s %s, ********************************************** warning app 0 has no item left in the queue\n", bptr, log_prefix); } } } if (found==1) { //current_node = hn; sfqdfull_virtual_time=next_queue_item->start_tag; fprintf(depthtrack,"%s %s dispatching tag %i app%i on %s\n", bptr, log_prefix, next_queue_item->socket_tag, next_queue_item->app_index, s_pool.socket_state_list[next_queue_item->request_socket_index].ip); int app_index=next_item->socket_data->app_index;; app_stats[app_index].req_go+=1; app_stats[app_index].dispatched_requests+=1; struct timeval dispatch_time, diff; gettimeofday(&dispatch_time, 0); next_queue_item->dispatchtime = dispatch_time; double ratio = ((float)(app_stats[0].dispatched_requests))/((float)app_stats[1].dispatched_requests); fprintf(stderr,"%s %s $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$ instant ratio is %d/%d=%f\n", bptr, log_prefix, app_stats[0].dispatched_requests, app_stats[1].dispatched_requests, ratio); return next_item; } else { sfqdfull_current_depth--; return NULL; } }
/**************************************************************************************** * Function name - tq_empty * * Description - Evaluates, whether a timer queue is empty * * Input - *tq - pointer to a timer queue, e.g. heap * Return Code/Output - If empty - positive value, if full - 0 ****************************************************************************************/ int tq_empty (timer_queue*const tq) { return heap_empty ((heap *const) tq); }
int router_nearest(struct router_t* router, const uint8_t id[N_NODEID], struct node_t* nodes[], size_t count) { int i, min, diff; uint8_t xor[N_NODEID]; heap_t* heap; struct rbitem_t* item; struct rbtree_node_t* node; const struct rbtree_node_t* prev; const struct rbtree_node_t* next; heap = heap_create(node_compare_less, (void*)id); heap_reserve(heap, count + 1); min = N_BITS; locker_lock(&router->locker); rbtree_find(&router->rbtree, id, &node); if (NULL == node) { locker_unlock(&router->locker); return 0; } item = rbtree_entry(node, struct rbitem_t, link); bitmap_xor(xor, id, item->node->id, N_BITS); diff = bitmap_count_leading_zero(xor, N_BITS); min = min < diff ? min : diff; heap_push(heap, item->node); prev = rbtree_prev(node); next = rbtree_next(node); do { while (prev) { item = rbtree_entry(prev, struct rbitem_t, link); bitmap_xor(xor, id, item->node->id, N_BITS); diff = bitmap_count_leading_zero(xor, N_BITS); heap_push(heap, item->node); if (heap_size(heap) > (int)count) heap_pop(heap); prev = rbtree_prev(prev); if (diff < min) { min = diff; break; // try right } } while (next) { item = rbtree_entry(next, struct rbitem_t, link); bitmap_xor(xor, id, item->node->id, N_BITS); diff = bitmap_count_leading_zero(xor, N_BITS); heap_push(heap, item->node); if (heap_size(heap) > (int)count) heap_pop(heap); next = rbtree_next(next); if (diff < min) { min = diff; break; // try left } } } while (heap_size(heap) < (int)count && (prev || next)); for (i = 0; i < (int)count && !heap_empty(heap); i++) { nodes[i] = heap_top(heap); node_addref(nodes[i]); heap_pop(heap); } locker_unlock(&router->locker); heap_destroy(heap); return i; }