-
Notifications
You must be signed in to change notification settings - Fork 0
/
queue.c
96 lines (77 loc) · 2.15 KB
/
queue.c
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
#include <errno.h>
#include <stdlib.h>
#include <stdio.h>
#include "queue.h"
#include "dep/sem.h"
static struct queueElement {
char *cmd;
char *out;
int flags;
struct queueElement *next;
} *head;
SEM *s;
SEM *readyToWrite;
int queue_init(void) {
s = semCreate(0);
if(!s) {
//errno already set by semCreate;
free(s);
return -1;
}
readyToWrite = semCreate(1);
if(!readyToWrite) {
//errno already set by semCreate;
free(readyToWrite);
return -1;
}
return 0;
}
void queue_deinit(void) {
free(s);
free(readyToWrite);
}
int queue_put(char *cmd, char *out, int flags) {
P(readyToWrite); //entering critical write area
struct queueElement *lauf = head;
struct queueElement *schlepp = NULL;
while (lauf) {
schlepp = lauf;
lauf = lauf->next;
}
lauf = malloc(sizeof(struct queueElement));
if (lauf == NULL) {
//TODO: errno =
return -1;
}
lauf->cmd = cmd;
lauf->out = out;
lauf->flags = flags;
lauf->next = NULL;
if (schlepp == NULL) {
head = lauf;
} else {
schlepp->next = lauf;
}
V(readyToWrite); //indicate completed write, next thread can add/read to/from queue
V(s); //indicate new item to be read in queue
return 0;
}
int queue_get(char **cmd, char **out, int *flags) {
P(s); //wait until an element is in list
P(readyToWrite); //entering critical area where queue might be changed
if(head) {
//write to pointer
*cmd = head->cmd;
*out = head->out;
*flags = head-> flags;
//remove from queue
struct queueElement *tmp = head; //save current element to free it later
head = head->next; //head either NULL if no further element was in queue (head->next would be NULL), or head is next element
//free queue element
free(tmp);
V(readyToWrite); //exiting critical area where queue might be changed
return 0;
}else{
return -1; //No element was in list despite it being indicated by semaphore (idk how that would even happen but error handling = good)
}
}