aboutsummaryrefslogtreecommitdiff
path: root/broccoli/fifoqueue.c
blob: 66764847c4041078b2b3624f38971f5ce4b76346 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
#include "includes/fifoqueue.h"
#include <pthread.h>

pthread_mutex_t lock;

    Fifo_q * 
init_queue(int size)
{
    Fifo_q * q = (Fifo_q *) malloc(sizeof(Fifo_q));
    q->head = NULL;
    q->tail = NULL;
    q->maxSize = size;
    q->currentSize = 0;

    if (pthread_mutex_init(&lock, NULL) != 0)
    {
        printf("WARNING: Couldn't initialize lock\n");
    }
    return q;
}

    boolean
is_full(Fifo_q * q)
{
    if(q->currentSize < q->maxSize)
        return false;
    else
        return true;
}  

    boolean
is_empty(Fifo_q * q)
{
    if(q->head==NULL)
        return true;
    else
        return false; 
}

    int
add_to_queue(Fifo_q * q, Sensor_t * sensor)
{

    pthread_mutex_lock(&lock);
    /* TODO delete first one if full */
    if(q == NULL){
        return -1;    
    } 
    else if(is_full(q)){
        return -1;
    }
    Queue_t * new_elem = (Queue_t *) malloc(sizeof(Queue_t *));
    new_elem->next = NULL;
    new_elem->sensor = sensor;
    if(is_empty(q))
        q->head = new_elem;
    else
        q->tail->next = new_elem;
    q->tail = new_elem;
    q->currentSize++;
    pthread_mutex_unlock(&lock);
    print_queue(q);
    return 1;
}

    Sensor_t *
pop_from_queue(Fifo_q * q)
{

    pthread_mutex_lock(&lock);
    if(is_empty(q)){
        perror("The queue is empty");
        exit(-1);
    }
    Queue_t * head = q->head;
    q->head = q->head->next;
    Sensor_t * sensor = head->sensor;
    free(head);
    q->currentSize--;
    pthread_mutex_unlock(&lock);
    return sensor;
} 

    Sensor_t *
create_sensor_object(int value, int uid){
    Sensor_t * sensor = (Sensor_t *) malloc(sizeof(Sensor_t *));
    sensor->value = value;
    sensor->uid = uid;
    return sensor;
}
    void
print_queue(Fifo_q * q)
{
    pthread_mutex_lock(&lock);
    Queue_t * current = q->head;
    if(current == NULL){
        printf("The queue is empty!");
        return;
    }
    while(current != NULL){
        printf("sensor value=%d, sensor uid=%d\n",
                current->sensor->value, current->sensor->uid);
        current = current->next;
    }
    pthread_mutex_unlock(&lock);
}