/*
* Copyright 2021 Jeisson Hidalgo-Cespedes - Universidad de Costa Rica
*/
#include <assert.h>
#include <pthread.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include "queue.h"
bool queue_is_empty_private(const queue_t* queue);
int queue_init(queue_t* queue) {
assert(queue);
queue->head = NULL;
queue->tail = NULL;
return pthread_mutex_init(&queue->mutex, /*attr*/NULL);
}
int queue_destroy(queue_t* queue) {
assert(queue);
queue_free(queue);
return pthread_mutex_destroy(&queue->mutex);
}
bool queue_is_empty_private(const queue_t* queue) {
assert(queue);
return queue->head == NULL;
}
int queue_append(queue_t* queue, data_t data) {
assert(queue);
int error = 0;
queue_node_t* new_node = (queue_node_t*)calloc(1, sizeof(queue_node_t));
if (new_node) {
new_node->product_number = data;
pthread_mutex_lock(&queue->mutex);
if (queue_is_empty_private(queue)) {
queue->head = queue->tail = new_node;
} else {
queue->tail = queue->tail->next = new_node;
}
pthread_mutex_unlock(&queue->mutex);
} else {
fprintf(stderr, "error: could not allocate memory for a queue node\n");
error = 41;
}
return error;
}
bool queue_is_empty(queue_t* queue) {
assert(queue);
pthread_mutex_lock(&queue->mutex);
bool result = queue->head == NULL;
pthread_mutex_unlock(&queue->mutex);
return result;
}
int queue_free(queue_t* queue) {
assert(queue);
pthread_mutex_lock(&queue->mutex);
queue_node_t* current = queue->head;
while (current) {
queue->head = current->next;
free(current);
current = queue->head;
}
queue->tail = NULL;
pthread_mutex_unlock(&queue->mutex);
return 0;
}
data_t queue_dequeue(queue_t* queue) {
assert(queue);
pthread_mutex_lock(&queue->mutex);
assert(queue_is_empty_private(queue) == false);
queue_node_t* first = queue->head;
data_t data = first->product_number;
queue->head = first->next;
free(first);
if (queue->head == NULL) {
queue->tail = NULL;
}
pthread_mutex_unlock(&queue->mutex);
return data;
}