void exampleQueue() { // Use pooling for efficiency, if you don't want to use pooling // then comment out this line. pool_queue(16); Queue* Q = newQueue(); // A queue with strings queue_offer(Q, "First"); queue_offer(Q, "In"); queue_offer(Q, "First"); queue_offer(Q, "Out."); // Peek at the head of the queue printf("%s\n", (char*)queue_peek(Q)); // Traverse through the queue polling each string while (!queue_isEmpty(Q)) printf("%s ", (char*)queue_poll(Q)); printf("\n"); // A queue with integers, primitive data types require some trickyness queue_clear(Q); int x[] = {1, 2}; int y = 3; queue_offer(Q, &x[0]); queue_offer(Q, &x[1]); queue_offer(Q, &y); while (!queue_isEmpty(Q)) // You first need to cast it using (int*) and since its a pointer to // an integer you need to get the value of the pointer using * // You could similarly use: // int* z = queue_poll(Q); // printf("%d ", *z); printf("%d ", *((int*)queue_poll(Q))); printf("\n"); // This will clear the queue of any nodes and pool them and then free // the queue itself from memory queue_free(Q); // If you're not using pooling this can be commented out. This will // free all pooled nodes from memory. Always call this at the end // of using any Queue. unpool_queue(); }
char * queue_remove(QUEUE * queue) { char * data; if (queue_isEmpty(queue)) return NULL; data = queue->data[queue->head]; queue->head = queue_next(queue->head, queue->size); return data; }
void queue_destroy(queue* q) { while(!queue_isEmpty(q)) { queue_dequeue(q); } free(q); }
int main () { queue_t* queuePtr; random_t* randomPtr; long data[] = {3, 1, 4, 1, 5}; long numData = sizeof(data) / sizeof(data[0]); long i; randomPtr = random_alloc(); assert(randomPtr); random_seed(randomPtr, 0); puts("Starting tests..."); queuePtr = queue_alloc(-1); assert(queue_isEmpty(queuePtr)); for (i = 0; i < numData; i++) { insertData(queuePtr, &data[i]); } assert(!queue_isEmpty(queuePtr)); for (i = 0; i < numData; i++) { long* dataPtr = (long*)queue_pop(queuePtr); printf("Removing %li: ", *dataPtr); printQueue(queuePtr); } assert(!queue_pop(queuePtr)); assert(queue_isEmpty(queuePtr)); puts("All tests passed."); for (i = 0; i < numData; i++) { insertData(queuePtr, &data[i]); } for (i = 0; i < numData; i++) { printf("Shuffle %li: ", i); queue_shuffle(queuePtr, randomPtr); printQueue(queuePtr); } assert(!queue_isEmpty(queuePtr)); queue_free(queuePtr); return 0; }
void mpu_init(void){ mpu_setup_s *startup_config; boolean is_Started; // allocate memory and set to zero mpu_regs = malloc(sizeof *mpu_regs); if(!mpu_regs){ while(1); } /* Configure mpu_regs to be a copy of onboard registers */ // mpu actually starts up with two non-zero registers mpu_regs->who_am_i = MPU_I2C_ADDRESS; // initialized with known address mpu_regs->pwr_mgmt_1 = BIT_SLEEP; // starts in sleep mode /* End configure of mpu_regs */ NVIC_SetPriority (EXTI9_5_IRQn, 0x07); /* set priority to lower than i2c */ NVIC_DisableIRQ(EXTI9_5_IRQn); /* we don't want to interrupt during setup */ /* Check to see if MPU is already loaded (from pre-CPU reset) */ is_Started = mpu_isInitialized(); // restart device enQueue(mpuTxQueue, reg.pwr_mgmt_1); // enqueue the register number enQueue(mpuTxQueue, BIT_RESET); // enqueue the new value mpu_writeRegister(1, reg.pwr_mgmt_1, false); // send to i2c interface Delay(1000);// wait for reset // wakeup device on restart mpu_regs->pwr_mgmt_1 &= MPU_WAKE_UP; enQueue(mpuTxQueue, reg.pwr_mgmt_1); // enqueue the register number enQueue(mpuTxQueue, mpu_regs->pwr_mgmt_1); // enqueue the new value mpu_writeRegister(1, reg.pwr_mgmt_1, false); // send to i2c interface Delay(500);// wait for wakeup mpu_readRegister(1, reg.pwr_mgmt_1); while(queue_isEmpty(mpuRxQueue)){ } display_Int(deQueue(mpuRxQueue), 0, 0, true); /* Once device is on and awake, set it to default config */ startup_config = malloc(sizeof *startup_config); startup_config->rate_div = STARTUP_RATE_DIV; startup_config->lpf = STARTUP_LPF; startup_config->user_ctrl = STARTUP_USERCTRL; startup_config->accel_cfg = STARTUP_ACCELCFG; startup_config->fifo_en = STARTUP_FIFOEN; startup_config->gyro_cfg = STARTUP_GYROCFG; startup_config->int_enable = STARTUP_INTNENABLE; startup_config->int_pin_cfg = STARTUP_INTPINCFG; configure_Mpu(startup_config); /* call the function to write values */ free(startup_config); /* release memory */ //NVIC_ClearPendingIRQ(EXTI9_5_IRQn); /* clear any initial interrupts */ NVIC_EnableIRQ(EXTI9_5_IRQn); /* turn interrupts back on */ }
/* ============================================================================= * net_findDescendants * -- Contents of bitmapPtr set to 1 if descendants, else 0 * -- Returns false if id is not root node (i.e., has cycle back id) * ============================================================================= */ bool_t net_findDescendants (net_t* netPtr, long id, bitmap_t* descendantBitmapPtr, queue_t* workQueuePtr) { bool_t status; vector_t* nodeVectorPtr = netPtr->nodeVectorPtr; assert(descendantBitmapPtr->numBit == vector_getSize(nodeVectorPtr)); bitmap_clearAll(descendantBitmapPtr); queue_clear(workQueuePtr); { net_node_t* nodePtr = (net_node_t*)vector_at(nodeVectorPtr, id); list_t* childIdListPtr = nodePtr->childIdListPtr; list_iter_t it; list_iter_reset(&it, childIdListPtr); while (list_iter_hasNext(&it, childIdListPtr)) { long childId = (long)list_iter_next(&it, childIdListPtr); status = bitmap_set(descendantBitmapPtr, childId); assert(status); status = queue_push(workQueuePtr, (void*)childId); assert(status); } } while (!queue_isEmpty(workQueuePtr)) { long childId = (long)queue_pop(workQueuePtr); if (childId == id) { queue_clear(workQueuePtr); return FALSE; } net_node_t* nodePtr = (net_node_t*)vector_at(nodeVectorPtr, childId); list_t* grandChildIdListPtr = nodePtr->childIdListPtr; list_iter_t it; list_iter_reset(&it, grandChildIdListPtr); while (list_iter_hasNext(&it, grandChildIdListPtr)) { long grandChildId = (long)list_iter_next(&it, grandChildIdListPtr); if (!bitmap_isSet(descendantBitmapPtr, grandChildId)) { status = bitmap_set(descendantBitmapPtr, grandChildId); assert(status); status = queue_push(workQueuePtr, (void*)grandChildId); assert(status); } } } return TRUE; }
/* ============================================================================= * net_findAncestors * -- Contents of bitmapPtr set to 1 if ancestor, else 0 * -- Returns false if id is not root node (i.e., has cycle back id) * ============================================================================= */ bool_t net_findAncestors (net_t* netPtr, long id, bitmap_t* ancestorBitmapPtr, queue_t* workQueuePtr) { bool_t status; vector_t* nodeVectorPtr = LocalLoad(&netPtr->nodeVectorPtr); assert(LocalLoad(&ancestorBitmapPtr->numBit) == vector_getSize(nodeVectorPtr)); bitmap_clearAll(ancestorBitmapPtr); queue_clear(workQueuePtr); { net_node_t* nodePtr = (net_node_t*)vector_at(nodeVectorPtr, id); list_t* parentIdListPtr = LocalLoad(&nodePtr->parentIdListPtr); list_iter_t it; list_iter_reset(&it, parentIdListPtr); while (list_iter_hasNext(&it, parentIdListPtr)) { long parentId = (long)list_iter_next(&it, parentIdListPtr); status = bitmap_set(ancestorBitmapPtr, parentId); assert(status); status = queue_push(workQueuePtr, (void*)parentId); assert(status); } } while (!queue_isEmpty(workQueuePtr)) { long parentId = (long)queue_pop(workQueuePtr); if (parentId == id) { queue_clear(workQueuePtr); return FALSE; } net_node_t* nodePtr = (net_node_t*)vector_at(nodeVectorPtr, parentId); list_t* grandParentIdListPtr = LocalLoad(&nodePtr->parentIdListPtr); list_iter_t it; list_iter_reset(&it, grandParentIdListPtr); while (list_iter_hasNext(&it, grandParentIdListPtr)) { long grandParentId = (long)list_iter_next(&it, grandParentIdListPtr); if (!bitmap_isSet(ancestorBitmapPtr, grandParentId)) { status = bitmap_set(ancestorBitmapPtr, grandParentId); assert(status); status = queue_push(workQueuePtr, (void*)grandParentId); assert(status); } } } return TRUE; }
bool queue_dequeue(visitor_t * visitor_deleted, queue_t * self) { node_t * pt; if(queue_isEmpty(self)) return (false); *visitor_deleted = self->front->visitor; pt = self->front; self->front = self->front->next; free(pt); self->items--; if(self->items==0) self->rear = NULL; return (true); }
void configure_Mpu(mpu_setup_s *config){ uint16_t numBytes; /* Configure the LPF and gyros/accels */ enQueue(mpuTxQueue, reg.rate_div); /* enqueue the register */ enQueue(mpuTxQueue, config->rate_div); /* enqueue values of regs */ enQueue(mpuTxQueue, config->lpf); /* enqueue values of regs */ enQueue(mpuTxQueue, config->gyro_cfg); enQueue(mpuTxQueue, config->accel_cfg); numBytes = 4; /* number of reg VALUES written */ mpu_writeRegister(numBytes, reg.lpf, false); /* can burst write consecutive regs */ /* Setup the fifo buffer on mpu */ enQueue(mpuTxQueue, reg.fifo_en); /* enqueue the register */ enQueue(mpuTxQueue, config->fifo_en); /* enqueue values of regs */ numBytes = 1; /* number of reg VALUES written */ mpu_writeRegister(numBytes, reg.fifo_en, false); /* can burst write consecutive regs */ /* Turn on/off device sectors */ enQueue(mpuTxQueue, reg.user_ctrl); /* enqueue the register */ enQueue(mpuTxQueue, config->user_ctrl); /* enqueue values of regs */ numBytes = 1; /* number of reg VALUES written */ mpu_writeRegister(numBytes, reg.user_ctrl, false); /* can burst write consecutive regs */ /* Configure interrupts and interrupt sources */ enQueue(mpuTxQueue, reg.int_pin_cfg); /* enqueue the register */ enQueue(mpuTxQueue, config->int_pin_cfg); /* enqueue values of regs */ enQueue(mpuTxQueue, config->int_enable); /* enqueue values of regs */ numBytes = 2; /* number of reg VALUES written */ mpu_writeRegister(numBytes, reg.int_pin_cfg, false); /* can burst write consecutive regs */ /* make sure to update local copy of configuration registers */ mpu_regs->lpf = config->lpf; mpu_regs->gyro_cfg = config->gyro_cfg; mpu_regs->accel_cfg = config->accel_cfg; mpu_regs->fifo_en = config->fifo_en; mpu_regs->int_pin_cfg = config->int_pin_cfg; mpu_regs->int_enable = config->int_enable; mpu_regs->user_ctrl = config->user_ctrl; data_packet_size = 0; if(mpu_regs->fifo_en & BIT_FIFO_EN_XYZG) data_packet_size += 3; if(mpu_regs->fifo_en & BIT_FIFO_EN_XYZA) data_packet_size += 3; while(!queue_isEmpty(mpuTxQueue)){} /* wait until the setup sequence is sent */ /* All done */ }
int queue_del(queue_t * selfQueue){ if(selfQueue != NULL){ if(queue_isEmpty(selfQueue)){ printf("Queue is empty. \n"); return; }else{ int temp = selfQueue->array[selfQueue->f]; selfQueue->array[selfQueue->f] = -1; selfQueue->f = (selfQueue->f + 1) % selfQueue->max_size; return temp; } }else{ printf("NULL POINTER"); exit(-1); } }
int main(void) { //queue_t *line; visitor_t *visitor = (visitor_t *) malloc(sizeof(visitor_t)); queue_t * line = queue_new(); char ch; queue_new(line); puts("put [a] to add a value."); puts("put [d] to delete a value"); puts("put [q] to quit the program."); while((ch = getchar()) != 'q') { if(ch != 'a' && ch != 'd') //ignore another stuff here continue; if(ch == 'a') { printf("What value you want to add: "); scanf("%d", visitor); if(!queue_isFull(line)) { printf("Adding %d into queue...\n", *visitor); queue_enqueue(*visitor, line); } else puts("Queue is full."); } else { if(queue_isEmpty(line)) puts("No items to delete."); else { queue_dequeue(visitor, line); printf("Deleting %d from the queue...\n", *visitor); } } printf("%d elements in the queue.\n", queue_itemCount(line)); puts("print [a] to add a value, [d] to delete a value, [q] to quit the program: "); } queue_delete(line); puts("End of the program"); return (0); }
int main() { const int SIZE = 6; QUEUE queue; queue.size = SIZE; queue_init(&queue); char isRunning = 1; while (isRunning) { int choice; char * data; printf("\n1. 삽입\n2. 꺼내기\n3. 출력\n4. 전부 삭제\n5. 끝\n입력: "); scanf("%d", &choice); getchar(); switch (choice) { case 1: if (queue_isFull(&queue)) { printf("큐가 꽉 찼습니다\n"); break; } printf("데이터를 입력해주세요: "); data = (char *) malloc(256); gets(data); queue_add(&queue, data); break; case 2: if (queue_isEmpty(&queue)) { printf("큐가 비었습니다\n"); break; } data = queue_remove(&queue); printf("읽은 데이터: %s\n", data); free(data); break; case 3: queue_print(&queue); break; case 4: // This doesn't free the queue, but whatever. queue_reset(&queue); break; case 5: isRunning = 0; break; } } }
/* ============================================================================= * net_isPath * ============================================================================= */ bool_t net_isPath (net_t* netPtr, long fromId, long toId, bitmap_t* visitedBitmapPtr, queue_t* workQueuePtr) { bool_t status; vector_t* nodeVectorPtr = netPtr->nodeVectorPtr; assert(visitedBitmapPtr->numBit == vector_getSize(nodeVectorPtr)); bitmap_clearAll(visitedBitmapPtr); queue_clear(workQueuePtr); status = queue_push(workQueuePtr, (void*)fromId); assert(status); while (!queue_isEmpty(workQueuePtr)) { long id = (long)queue_pop(workQueuePtr); if (id == toId) { queue_clear(workQueuePtr); return TRUE; } status = bitmap_set(visitedBitmapPtr, id); assert(status); net_node_t* nodePtr = (net_node_t*)vector_at(nodeVectorPtr, id); list_t* childIdListPtr = nodePtr->childIdListPtr; list_iter_t it; list_iter_reset(&it, childIdListPtr); while (list_iter_hasNext(&it, childIdListPtr)) { long childId = (long)list_iter_next(&it, childIdListPtr); if (!bitmap_isSet(visitedBitmapPtr, childId)) { status = queue_push(workQueuePtr, (void*)childId); assert(status); } } } return FALSE; }
bool queue_enqueue(visitor_t * visitor, queue_t * self) { node_t * pnew; if(queue_isFull(self)) return (false); pnew = (node_t *) malloc(sizeof(node_t)); if(NULL == pnew) { fprintf(stderr, "Cannot reserve memory for pointer.\n"); exit(1); } pnew->visitor = *visitor; pnew->next = NULL; if(queue_isEmpty(self)) self->front = pnew; else self->rear->next = pnew; self->rear = pnew; self->items++; return (true); }
/* ============================================================================= * data_generate * -- Binary variables of random PDFs * -- If seed is <0, do not reseed * -- Returns random network * ============================================================================= */ net_t* data_generate (data_t* dataPtr, long seed, long maxNumParent, long percentParent) { random_t* randomPtr = dataPtr->randomPtr; if (seed >= 0) { random_seed(randomPtr, seed); } /* * Generate random Bayesian network */ long numVar = dataPtr->numVar; net_t* netPtr = net_alloc(numVar); assert(netPtr); net_generateRandomEdges(netPtr, maxNumParent, percentParent, randomPtr); /* * Create a threshold for each of the possible permutation of variable * value instances */ long** thresholdsTable = (long**)SEQ_MALLOC(numVar * sizeof(long*)); assert(thresholdsTable); long v; for (v = 0; v < numVar; v++) { list_t* parentIdListPtr = net_getParentIdListPtr(netPtr, v); long numThreshold = 1 << list_getSize(parentIdListPtr); long* thresholds = (long*)SEQ_MALLOC(numThreshold * sizeof(long)); assert(thresholds); long t; for (t = 0; t < numThreshold; t++) { long threshold = random_generate(randomPtr) % (DATA_PRECISION + 1); thresholds[t] = threshold; } thresholdsTable[v] = thresholds; } /* * Create variable dependency ordering for record generation */ long* order = (long*)SEQ_MALLOC(numVar * sizeof(long)); assert(order); long numOrder = 0; queue_t* workQueuePtr = queue_alloc(-1); assert(workQueuePtr); vector_t* dependencyVectorPtr = vector_alloc(1); assert(dependencyVectorPtr); bitmap_t* orderedBitmapPtr = bitmap_alloc(numVar); assert(orderedBitmapPtr); bitmap_clearAll(orderedBitmapPtr); bitmap_t* doneBitmapPtr = bitmap_alloc(numVar); assert(doneBitmapPtr); bitmap_clearAll(doneBitmapPtr); v = -1; while ((v = bitmap_findClear(doneBitmapPtr, (v + 1))) >= 0) { list_t* childIdListPtr = net_getChildIdListPtr(netPtr, v); long numChild = list_getSize(childIdListPtr); if (numChild == 0) { bool status; /* * Use breadth-first search to find net connected to this leaf */ queue_clear(workQueuePtr); status = queue_push(workQueuePtr, (void*)v); assert(status); while (!queue_isEmpty(workQueuePtr)) { long id = (long)queue_pop(workQueuePtr); status = bitmap_set(doneBitmapPtr, id); assert(status); status = vector_pushBack(dependencyVectorPtr, (void*)id); assert(status); list_t* parentIdListPtr = net_getParentIdListPtr(netPtr, id); list_iter_t it; list_iter_reset(&it, parentIdListPtr); while (list_iter_hasNext(&it, parentIdListPtr)) { long parentId = (long)list_iter_next(&it, parentIdListPtr); status = queue_push(workQueuePtr, (void*)parentId); assert(status); } } /* * Create ordering */ long i; long n = vector_getSize(dependencyVectorPtr); for (i = 0; i < n; i++) { long id = (long)vector_popBack(dependencyVectorPtr); if (!bitmap_isSet(orderedBitmapPtr, id)) { bitmap_set(orderedBitmapPtr, id); order[numOrder++] = id; } } } } assert(numOrder == numVar); /* * Create records */ char* record = dataPtr->records; long r; long numRecord = dataPtr->numRecord; for (r = 0; r < numRecord; r++) { long o; for (o = 0; o < numOrder; o++) { long v = order[o]; list_t* parentIdListPtr = net_getParentIdListPtr(netPtr, v); long index = 0; list_iter_t it; list_iter_reset(&it, parentIdListPtr); while (list_iter_hasNext(&it, parentIdListPtr)) { long parentId = (long)list_iter_next(&it, parentIdListPtr); long value = record[parentId]; assert(value != DATA_INIT); index = (index << 1) + value; } long rnd = random_generate(randomPtr) % DATA_PRECISION; long threshold = thresholdsTable[v][index]; record[v] = ((rnd < threshold) ? 1 : 0); } record += numVar; assert(record <= (dataPtr->records + numRecord * numVar)); } /* * Clean up */ bitmap_free(doneBitmapPtr); bitmap_free(orderedBitmapPtr); vector_free(dependencyVectorPtr); queue_free(workQueuePtr); SEQ_FREE(order); for (v = 0; v < numVar; v++) { SEQ_FREE(thresholdsTable[v]); } SEQ_FREE(thresholdsTable); return netPtr; }
int queue_deleteTail(queue_t self){ if (queue_isEmpty(self)) return QUEUE_ERROR; int res = self->queue[self->size - 1]; self->size--; return res; }
void queue_delete(queue_t * self) { visitor_t tmp; while(!queue_isEmpty(self)) queue_dequeue(&tmp, self); }
int main(int argc, char *argv[]) { char command[32]; int eventsNr, eventId, procId, priority; int i, iteration; TStack **eventsStacks; TQueue *procQ; // Daca nu exista destule argumente la rularea programului, atunci opreste executia if (argc < 3) { printf("Argumente insuficiente!\n"); return -1; } // Seteaza fisierele de intrare si de iesire freopen(argv[1], "r", stdin); freopen(argv[2], "w", stdout); // Citeste numarul de event-uri si creeaza stivele lor fscanf(stdin, "%d", &eventsNr); eventsStacks = calloc(eventsNr, sizeof(TStack*)); for (i = 0; i < eventsNr; i++) { eventsStacks[i] = stack_new(sizeof(TProcess)); } // Creeaza coada de prioritati procQ = queue_new(sizeof(TProcess), compare_process); // Citeste si executa comenzile din fisierul de intrare iteration = 0; while (fscanf(stdin, "%s", command) != EOF) { iteration++; if (strcmp(command, "start") == 0) { fscanf(stdin, "%d", &procId); fscanf(stdin, "%d", &priority); // Creeaza un proces TProcess p; p.id = procId; p.priority = priority; p.iteration = iteration; // Introduce procesul creat in coada de prioritati queue_push(procQ, &p); } else if (strcmp(command, "wait") == 0) { fscanf(stdin, "%d", &eventId); fscanf(stdin, "%d", &procId); // Creaza o stiva auxiliara TStack *aux = stack_new(sizeof(TProcess)); // Muta procesele in stiva auxiliara pana cand procesul // cautat este gasit si mutat in stiva evenimentului TProcess *p; while (!queue_isEmpty(procQ)) { p = queue_pop(procQ); if (p->id == procId) { stack_push(eventsStacks[eventId], p); free_process(p); break; } stack_push(aux, p); free_process(p); } // Muta procesele din stiva auxiliara inapoi in coada // de prioritati while (!stack_isEmpty(aux)) { p = stack_pop(aux); queue_push(procQ, p); free_process(p); } // Distruge stiva auxiliara stack_destroy(&aux, free_process); } else if (strcmp(command, "event") == 0) { fscanf(stdin, "%d", &eventId); // Muta procesele din stiva evenimentului in coada // de prioritati TProcess *p; while (!stack_isEmpty(eventsStacks[eventId])) { p = stack_pop(eventsStacks[eventId]); queue_push(procQ, p); free_process(p); } } else if (strcmp(command, "end") == 0) { fscanf(stdin, "%d", &procId); // Creaza o stiva auxiliara TStack *aux = stack_new(sizeof(TProcess)); // Muta procesele in stiva auxiliara pana cand procesul // cautat este gasit si sters TProcess *p; while (!queue_isEmpty(procQ)) { p = queue_pop(procQ); if (p->id == procId) { free_process(p); break; } stack_push(aux, p); free_process(p); } // Muta procesele din stiva auxiliara inapoi in coada // de prioritati while (!stack_isEmpty(aux)) { p = stack_pop(aux); queue_push(procQ, p); free_process(p); } // Distruge stiva auxiliara stack_destroy(&aux, free_process); } // Afiseaza iteratia printf("%d\n", iteration); // Afiseaza coada de prioritati if (!queue_isEmpty(procQ)) { queue_print(procQ, print_process); } else { printf("\n"); } // Afiseaza stivele for (i = 0; i < eventsNr; i++) { if (!stack_isEmpty(eventsStacks[i])) { printf("%d: ", i); stack_print(eventsStacks[i], print_process); } } printf("\n"); } // Elibereaza memoria queue_destroy(&procQ, free_process); for (i = 0; i < eventsNr; i++) { stack_destroy(&eventsStacks[i], free_process); } free(eventsStacks); return 0; }