int nextTwoAreAndRemove(Parser *parser, TokenType first, TokenType second) { Token *tok_1, *tok_2; NULL_CHECK(parser->tok_q, "Unexpected EOF!"); if (2 > parser->tok_q->size) { return FALSE; } tok_1 = queue_peek(parser->tok_q); if (first != tok_1->type) { return FALSE; } queue_remove(parser->tok_q); tok_2 = queue_peek(parser->tok_q); if (second != tok_2->type) { queue_add_front(parser->tok_q, tok_1); return FALSE; } queue_remove(parser->tok_q); free(tok_1); free(tok_2); return TRUE; }
/* espeak_thread is the "main" function of our secondary (queue-processing) * thread. * First, lock queue_guard, because it needs to be locked when we call * pthread_cond_wait on the runner_awake condition variable. * Next, enter an infinite loop. * The wait call also unlocks queue_guard, so that the other thread can * manipulate the queue. * When runner_awake is signaled, the pthread_cond_wait call re-locks * queue_guard, and the "queue processor" thread has access to the queue. * While there is an entry in the queue, call queue_process_entry. * queue_process_entry unlocks queue_guard after removing an item from the * queue, so that the main thread doesn't have to wait for us to finish * processing the entry. So re-lock queue_guard after each call to * queue_process_entry. * * The main thread can add items to the queue in exactly two situations: * 1. We are waiting on runner_awake, or * 2. We are processing an entry that has just been removed from the queue. */ void *espeak_thread(void *arg) { struct synth_t *s = (struct synth_t *) arg; pthread_mutex_lock(&queue_guard); while (should_run) { while (should_run && !queue_peek(synth_queue) && !stop_requested) pthread_cond_wait(&runner_awake, &queue_guard); if (stop_requested) { stop_speech(); synth_queue_clear(); stop_requested = 0; pthread_cond_signal(&stop_acknowledged); } while (should_run && queue_peek(synth_queue) && !stop_requested) { queue_process_entry(s); pthread_mutex_lock(&queue_guard); } } pthread_cond_signal(&stop_acknowledged); pthread_mutex_unlock(&queue_guard); return NULL; }
int nextIsAndSecondIsntAndRemove(Parser *parser, TokenType first, TokenType notSecond) { Token *tok_1, *tok_2; NULL_CHECK(parser->tok_q, "Unexpected EOF!"); if (1 > parser->tok_q->size) { return FALSE; } tok_1 = queue_peek(parser->tok_q); if (first != tok_1->type) { return FALSE; } queue_remove(parser->tok_q); if (0 == parser->tok_q->size) { return TRUE; } tok_2 = queue_peek(parser->tok_q); if (notSecond == tok_2->type) { queue_add_front(parser->tok_q, tok_1); return FALSE; } free(tok_1); return TRUE; }
void queue_test_peek(void) { queue_t* q = queue_init(q_compare, q_print, q_clone, q_destroy); CU_ASSERT (q != NULL); CU_ASSERT (queue_peek(NULL) == NULL); CU_ASSERT (queue_push(q, queue_test_s1) != NULL); CU_ASSERT (queue_push(q, queue_test_s2) != NULL); CU_ASSERT (queue_push(q, queue_test_s3) != NULL); CU_ASSERT (queue_push(q, queue_test_s4) != NULL); char* str = queue_peek(q); CU_ASSERT(str == queue_test_s1); CU_ASSERT (strcmp(str, queue_test_s1) == 0); str = queue_pop(q); CU_ASSERT(str != queue_test_s1); CU_ASSERT (strcmp(str, queue_test_s1) == 0); free(str); str = queue_peek(q); CU_ASSERT(str == queue_test_s2); CU_ASSERT (strcmp(str, queue_test_s2) == 0); CU_ASSERT (queue_destroy(q) == 0); }
time_t ev_timeout_process (void) { char *fn = "ev_timeout_process()"; Ev_TO_Data *td_tmp; while ((td_tmp = (Ev_TO_Data *) queue_peek (ev_to_queue)) && (td_tmp->at <= time (NULL))) { /* process the event */ td_tmp = dequeue (ev_to_queue); /* call timeout handler, if any */ if (td_tmp->handler) { if (T.debug > 3) syslog (LOG_DEBUG, "%s: call timeout handler", fn); (td_tmp->handler) (td_tmp); } else if (T.debug > 3) syslog (LOG_DEBUG, "%s: cancel timeout event", fn); ev_to_data_free (td_tmp); } td_tmp = (Ev_TO_Data *) queue_peek (ev_to_queue); if (td_tmp) return td_tmp->at; /* next event scheduled time */ else return 0; /* no event scheduled */ }
int main() { node* queue = new_queue(); int i; for (i=0; i<10; i++) { enqueue(queue, i); } assert(queue_peek(queue) == 0); assert(dequeue(queue) == 0); assert(queue_peek(queue) == 1); }
static void red_stack_spi_handle_reset(void) { int slave; stack_announce_disconnect(&_red_stack.base); _red_stack.base.recipients.count = 0; log_info("Starting reinitialization of SPI slaves"); // Someone pressed reset we have to wait until he stops pressing while (gpio_input(_red_stack_reset_stack_pin) == 0) { // Wait 100us and check again. We wait as long as the user presses the button SLEEP_NS(0, 1000*100); } SLEEP_NS(1, 1000*1000*500); // Wait 1.5s so slaves can start properly // Reinitialize slaves _red_stack.slave_num = 0; for (slave = 0; slave < RED_STACK_SPI_MAX_SLAVES; slave++) { _red_stack.slaves[slave].stack_address = slave; _red_stack.slaves[slave].status = RED_STACK_SLAVE_STATUS_ABSENT; _red_stack.slaves[slave].sequence_number_master = 1; _red_stack.slaves[slave].sequence_number_slave = 0; _red_stack.slaves[slave].next_packet_empty = false; // Unfortunately we have to discard all of the queued packets. // we can't be sure that the packets are for the correct slave after a reset. while (queue_peek(&_red_stack.slaves[slave].packet_to_spi_queue) != NULL) { queue_pop(&_red_stack.slaves[slave].packet_to_spi_queue, NULL); } } }
void recorrerNivel(int socketNivel, int socketPlanificador, int socketOrquestador) { Nivel *nivel = queue_peek(personaje->listaNiveles); Posicion* posicion = malloc(sizeof(Posicion)); Posicion* posicionActual = malloc(sizeof(Posicion)); t_queue *objetosABuscar = queue_create(); copiarCola(nivel->objetos, objetosABuscar); posicionActual->x = 0; posicionActual->y = 0; notificarIngresoAlNivel(socketNivel); esperarConfirmacion(socketNivel); log_debug(logger, "Confirmacion del nivel"); notificarIngresoAlNivel(socketPlanificador); esperarConfirmacion(socketPlanificador); log_debug(logger, "Confirmacion del Planificador"); int ubicacionCorrecta; int terminoPorDesbloqueo = false; log_debug(logger, "El personaje:(%s) empieza a recorrer el nivel (%s)", personaje->nombre, nivel->nombre); while (!queue_is_empty(objetosABuscar)) { char *cajaABuscar; ubicacionCorrecta = 0; while (!ubicacionCorrecta && !queue_is_empty(objetosABuscar)) { cajaABuscar = queue_pop(objetosABuscar); log_debug(logger, "Consultando ubicacion de la proxima caja del recurso (%s)", cajaABuscar); ubicacionCorrecta = consultarUbicacionCaja(*cajaABuscar, socketNivel, posicion); } if (estaEnPosicionDeLaCaja(posicion, posicionActual) && ubicacionCorrecta) { esperarConfirmacionDelPlanificador(socketPlanificador); terminoPorDesbloqueo = procesarPedidoDeRecurso(cajaABuscar, nivel, socketNivel, objetosABuscar, socketPlanificador, socketOrquestador); } while (!estaEnPosicionDeLaCaja(posicion, posicionActual) && ubicacionCorrecta) { log_debug(logger, "El personaje:(%s) esta a la espera de la confirmacion de movimiento", personaje->nombre); esperarConfirmacionDelPlanificador(socketPlanificador); log_debug(logger, "El personaje:(%s) tiene movimiento permitido, se procede a moverse", personaje->nombre); realizarMovimiento(posicionActual, posicion, socketNivel); log_debug(logger, "El personaje:(%s) se movio satisfactoriamente", personaje->nombre); if (estaEnPosicionDeLaCaja(posicion, posicionActual)) { terminoPorDesbloqueo = procesarPedidoDeRecurso(cajaABuscar, nivel, socketNivel, objetosABuscar, socketPlanificador, socketOrquestador); } else { movimientoRealizado(socketPlanificador); } } if (queue_is_empty(objetosABuscar) && !terminoPorDesbloqueo) { log_debug(logger, "El personaje: (%s) procede a informar la finalizacion del nivel al planificador.", personaje->nombre); MPS_MSG* mensajeAEnviar = malloc(sizeof(MPS_MSG)); mensajeAEnviar->PayloadDescriptor = FINALIZAR; mensajeAEnviar->PayLoadLength = sizeof(char); mensajeAEnviar->Payload = "4"; enviarMensaje(socketPlanificador, mensajeAEnviar); close(socketPlanificador); } } nivelTerminado(socketNivel); close(socketNivel); queue_pop(personaje->listaNiveles); free(posicion); free(nivel); }
void *queue_peek_ts(queue_t *queue , status_t *status ) { status_t local_status ; void *tail ; int tmp ; { #line 383 tmp = pthread_mutex_lock(& queue->mutex); #line 383 local_status = (status_t )tmp; #line 384 if (local_status != 0U) { #line 385 *status = local_status; #line 386 return ((void *)0); } #line 389 tail = queue_peek(queue, status); #line 391 pthread_mutex_unlock(& queue->mutex); #line 393 return (tail); } }
BUFFER *queue_get(QUEUE *q) { BUFFER *buf; buf = queue_peek(q); if (buf) queue_remove(q,buf); return buf; }
int main() { char buf[MSG_SIZE]; int ch, e; queue q; printf("\n 1 - Enque"); printf("\n 2 - Deque"); printf("\n 3 - Front element"); printf("\n 4 - Empty"); printf("\n 5 - Exit"); printf("\n 6 - Display"); printf("\n 7 - Queue size"); queue_create(&q); while (1) { printf("\n Enter choice : "); scanf("%d", &ch); switch (ch) { case 1: printf("Enter data : "); scanf("%s", buf); queue_enq(&q, buf); break; case 2: e = queue_deq(&q, buf); puts(buf); if (e == 0) printf("Front element : %s", buf); else printf("\n No front element in Queue as queue is empty"); break; case 3: e = queue_peek(&q, buf); puts(buf); if (e == 0) printf("Front element : %s", buf); else printf("\n No front element in Queue as queue is empty"); break; case 4: queue_empty(&q); break; case 5: exit(0); case 6: queue_display(&q); break; case 7: queue_size(&q); break; default: printf("Wrong choice, Please enter correct choice "); break; } } return 0; }
static void synth_queue_clear() { struct espeak_entry_t *current; while (queue_peek(synth_queue)) { current = (struct espeak_entry_t *) queue_remove(synth_queue); free_espeak_entry(current); } }
static void queue_process_entry(struct synth_t *s) { espeak_ERROR error; static struct espeak_entry_t *current = NULL; if (current != queue_peek(synth_queue)) { if (current) free_espeak_entry(current); current = (struct espeak_entry_t *) queue_remove(synth_queue); } pthread_mutex_unlock(&queue_guard); if (current->cmd != CMD_PAUSE && paused_espeak) { reinitialize_espeak(s); } switch (current->cmd) { case CMD_SET_FREQUENCY: error = set_frequency(s, current->value, current->adjust); break; case CMD_SET_PITCH: error = set_pitch(s, current->value, current->adjust); break; case CMD_SET_PUNCTUATION: error = set_punctuation(s, current->value, current->adjust); break; case CMD_SET_RATE: error = set_rate(s, current->value, current->adjust); break; case CMD_SET_VOICE: error = EE_OK; break; case CMD_SET_VOLUME: error = set_volume(s, current->value, current->adjust); break; case CMD_SPEAK_TEXT: s->buf = current->buf; s->len = current->len; error = speak_text(s); break; case CMD_PAUSE: if (!paused_espeak) { espeak_Cancel(); espeak_Terminate(); paused_espeak = 1; } break; default: break; } if (error == EE_OK) { free_espeak_entry(current); current = NULL; } }
void queue_test_empty(void) { queue_t* q = queue_init(q_compare, q_print, q_clone, q_destroy); CU_ASSERT (q != NULL); q_print(q, stderr); CU_ASSERT (queue_peek(q) == NULL); CU_ASSERT (queue_pop(q) == NULL); CU_ASSERT (queue_destroy(q) == 0); }
void bank_queuing(void) { int i; time_t time_iter = 0; int enter_new_custome = 0; int enter_customers = 0; int total_customers = 0; time_t total_delay_time = 0; queue_t bank_win[BANK_WINDOWS]; for (i = 0; i < BANK_WINDOWS; ++i) bank_win[i] = queue_create(); srand(time(0)); while (time_iter < TOTAL_WORK_TIME) { enter_new_custome = rand() % 2; if (enter_new_custome) { int q_idx; bank_customer_t customer = (bank_customer_t)malloc(sizeof(*customer)); customer->enter_time = time_iter; customer->trade_time = rand() % 10; q_idx = get_shortest_queue(bank_win); solve_bank_business(EVENT_ENTER, bank_win[q_idx], customer, time_iter, NULL, NULL); ++enter_customers; } for (i = 0; i < BANK_WINDOWS; ++i) { if (queue_empty(bank_win[i])) continue; bank_customer_t c = (bank_customer_t)queue_peek(bank_win[i]); if (time_iter - c->enter_time == c->trade_time) solve_bank_business(EVENT_LEAVE, bank_win[i], NULL, time_iter, &total_delay_time, &total_customers); } ++time_iter; } for (i = 0; i < BANK_WINDOWS; ++i) { while (!queue_empty(bank_win[i])) free(queue_dequeue(bank_win[i])); queue_delete(&bank_win[i]); } fprintf(stdout, "total time : %ld, enter customer: %d, " "total customer : %d, avg time : %lf\n", total_delay_time, enter_customers, total_customers, (double)total_delay_time / (double)total_customers); }
static void websocket_send_queued_data(Websocket *websocket) { WebsocketQueuedData *queued_data; while (websocket->send_queue.count > 0) { queued_data = queue_peek(&websocket->send_queue); websocket_send_frame(websocket, queued_data->buffer, queued_data->length); queue_pop(&websocket->send_queue, websocket_free_queued_data); } }
int main(void) { A* a = malloc(sizeof(A)), *b = malloc(sizeof(A)), *c = NULL; List* l = list_init(); Stack* s = stack_init(); Queue* q = queue_init(); DoubleLinkedList* d = dll_init(); printf("a: %d\nB: %d\nc: %d\n", (int)a, (int)b, (int)c); a->a1 = 1; a->a2 = 'c'; b->a1 = 2; b->a2 = 'a'; printf("\n=== LIST TEST ===\n"); list_add(l, a, 0); list_append(l, b); list_remove(l, 0); list_print(l); c = list_get(l, 0); printf("c: %d\n", (int)c); list_delete(l); printf("\n=== STACK TEST ===\n"); stack_push(s, b); stack_push(s, a); stack_pop(s); stack_print(s); c = stack_peek(s); printf("c: %d\n", (int)c); stack_delete(s); printf("\n=== QUEUE TEST ===\n"); queue_push(q, a); queue_push(q, b); queue_pop(q); queue_print(q); c = queue_peek(q); printf("c: %d\n", (int)c); queue_delete(q); printf("\n=== DOUBLE LINKED LIST TEST ===\n"); dll_add(d, b, 0); dll_prepend(d, a); dll_remove(d, 1); dll_print(d); c = dll_get(d, 0); printf("c: %d\n", (int)c); dll_delete(d); free(a); free(b); return 0; }
void remove_if_present(Parser *parser, TokenType type) { Token *tok; NULL_CHECK(parser->tok_q, "Unexpected EOF!"); if (0 == parser->tok_q->size) { return; } tok = queue_peek(parser->tok_q); if (type == tok->type) { queue_remove(parser->tok_q); free(tok); } }
void planificar_turnos(t_planificador **direccion_planificador) { t_planificador *planificador; planificador= *direccion_planificador; t_setColas *set = planificador->setColas; if (!queue_is_empty(set->colaListos)) //Si hay personajes listos para planificar. { if((planificador->socketPersonajeActual == -1 || (planificador->quantumsRestantes)==0)) //Si todavia nunca planifico o ya no quedan quantums { pthread_mutex_lock(&set->semaforo); sem_wait(&set->contadorDeListos); planificador->socketPersonajeActual =((t_personaje*) queue_peek(set->colaListos))->socket; //Miro al primer personaje de la cola sem_post(&set->contadorDeListos); pthread_mutex_unlock(&set->semaforo); planificador->quantumsRestantes=quantum; //Restauro el valor original de quantum } int respuestaDeTurno = enviar_permisoDeMovimiento(&planificador); //Le envio el turno (planificador->quantumsRestantes)--; //Decremento el quantum if(respuestaDeTurno == -1) //Si hubo algún error (el personaje se desconectó o no pudo responder por algún otro motivo) { t_personaje *personajeFalla; pthread_mutex_lock(&set->semaforo); sem_wait(&set->contadorDeListos); personajeFalla = (t_personaje *) queue_pop(set->colaListos); //Saco al personaje de la cola pthread_mutex_unlock(&set->semaforo); close(planificador->socketPersonajeActual);//Cierro su socket int _es_el_personaje(t_personaje* alguien) { return string_equals_ignore_case(alguien->remitente,personajeFalla->remitente); } pthread_mutex_lock(&semaforoConexiones); list_remove_by_condition(todosLosPersonajesConectados, (void*) _es_el_personaje); //Lo saco de los conectados log_info(planificador->logger,"%s se sacó de la lista de personajes conectados y de cola de listos porque hubo un error en recibir la respuesta de turno. \n", personajeFalla->remitente); loguearConectados(planificador); pthread_mutex_unlock(&semaforoConexiones); free(personajeFalla->remitente); free(personajeFalla); } else //Si no hubo errores { if(respuestaDeTurno==1) //Si luego del turno el personaje se bloqueó
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(); }
static struct list_head *queue_pop(struct queue *q) { struct list_head *r = queue_peek(q); if (r) { list_del(r); /* have we just emptied the bottom level? */ if (list_empty(q->qs)) queue_shift_down(q); } return r; }
void finish_SRTN(int id) { if (queue_peek(q) == NULL || q->head->task.id != id) { printf("Queue either empty, or the process with the given id is not the current head of the Queue!\n"); return; } Element *el = queue_poll(q); free(el); if (queue_size(q)){ switch_task(q->head->task.id); }else{ switch_task(IDLE); free_SRTN(); } }
void i2c_task(void *params) { I2COperation op; while (TRUE) { state = I2C_STATE_IDLE; queue_peek(op_queue, &op, PORT_MAX_DELAY); // do operation here semaphore_give(op_signal); queue_receive(op_queue, &op, 0); } }
static void bricklet_stack_check_request_queue(BrickletStack *bricklet_stack) { if(bricklet_stack->buffer_send_length != 0) { return; } mutex_lock(&bricklet_stack->request_queue_mutex); Packet *request = queue_peek(&bricklet_stack->request_queue); mutex_unlock(&bricklet_stack->request_queue_mutex); if(request != NULL) { bricklet_stack_send_ack_and_message(bricklet_stack, (uint8_t*)request, request->header.length); mutex_lock(&bricklet_stack->request_queue_mutex); queue_pop(&bricklet_stack->request_queue, NULL); mutex_unlock(&bricklet_stack->request_queue_mutex); } }
int nextIsAndRemove(Parser *parser, TokenType type) { Token *tok; NULL_CHECK(parser->tok_q, "Unexpected EOF!"); if (1 > parser->tok_q->size) { return FALSE; } tok = queue_peek(parser->tok_q); if (type != tok->type) { return FALSE; } queue_remove(parser->tok_q); free(tok); return TRUE; }
int nextIsWordAndRemove(Parser *parser, char word[]) { Token *tok; NULL_CHECK(parser->tok_q, "Unexpected EOF!"); if (1 > parser->tok_q->size) { return FALSE; } tok = queue_peek(parser->tok_q); if (WORD != tok->type || !MATCHES(word, tok->text)) { return FALSE; } queue_remove(parser->tok_q); free(tok); return TRUE; }
int main(int argc, char **argv) { struct Queue * q; struct QueueData d; int64_t l = 0; int64_t j = 0; char *cq = NULL; int opt = 0; while((opt = getopt(argc, argv, "hq:")) != -1) switch(opt) { case 'q': cq = strdup(optarg); break; default: case 'h': puts("Usage: qpeek [-h] [-q queue-name] [--] <args>"); return EXIT_FAILURE; } int i = optind-1; q = queue_open(SELECTQUEUE(cq)); if(0 == queue_is_opened(q)) { fprintf(stderr,"Failed to open the queue:%s\n", queue_get_last_error(q)); closequeue(q); return EXIT_FAILURE; } if(queue_len(q, &l) != LIBQUEUE_SUCCESS) { puts("Failed to read the queue length."); closequeue(q); return EXIT_FAILURE; } while(argv[++i]) { if((j = (int64_t)atoi((const char*)argv[i])) < 0 || (j+1)>l) { printf("Index out of bounds: %lld (%lld)\n", (long long)j, (long long)l); continue; } if(queue_peek(q, j-1, &d) != LIBQUEUE_SUCCESS) { printf("Failed to peek at element #%lld\n",(long long) j); } else printf("%s\n", (const char*)d.v); if(cq != NULL) free(cq); } return closequeue(q); }
int lrucache_set(LRUCACHE* lrucache, char* key, char* value) { char* k; while (map_length(lrucache->map) >= lrucache->size) { k = queue_peek(lrucache->queue); if (k == NULL) { break; } else { map_remove(lrucache->map, k); } } queue_insert(lrucache->queue, key); return map_set(lrucache->map, key, value); }
void test_empty (queue_t queue) { /* Test size empty*/ if (queue_size (queue) != 0) { printf ("Empty Queue: Size Failed\n"); exit (EXIT_FAILURE); } /* Test peek and deq */ if (queue_peek (queue) != NULL || queue_deq (queue) != NULL) { printf ("Empty Queue: Peek / Deq Failed\n"); exit (EXIT_FAILURE); } }
double conveyor_get_outflux( struct conveyor *conv ) { struct conveyor_object *obj; double ret = 0.0; while ((obj = queue_peek(conv->queue)) != NULL) { /* Oldest object is not yet done */ if (obj->limit > conv->time) break; /* Dequeue and add the value to the return value */ obj = dequeue(conv->queue); ret += obj->value; } /* Return object value plus any other conveyor objects ready to be released */ return ret; }