-
Notifications
You must be signed in to change notification settings - Fork 1
/
queue.c
120 lines (94 loc) · 2.39 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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
/**
* queue.c
*
* This file contains the implementation of the job queue
*/
#define MAX_NUM_NODES 100000
// The Node of a Queue
typedef struct Node {
dispatch_fn func;
void * func_arg;
struct Node * next;
struct Node * prev;
} Node;
// The Queue Struct
typedef struct Queue {
struct Node * head;
struct Node * tail;
int size;
int totalAdded;
int maxSize;
} Queue;
// Create a new queue
struct Queue * makeQueue() {
//fprintf(stdout,"makeQueue\n");
// Allocate memory for queue
Queue * q = (Queue *) malloc(sizeof(Queue));
//fprintf(stdout,"made it through malloc\n");
// Initialize the variables
q->size = 0;
q->totalAdded = 0;
q->maxSize = MAX_NUM_NODES;
q->head = NULL;
q->tail = NULL;
// Return the initialized queue
return q;
}
// Add a job to the queue
void addJob(Queue * q, dispatch_fn func, void * arg) {
// fprintf(stdout,"Queue Size: %d/%d\n",q->size,q->totalAdded);
//fprintf(stdout,"addJob\n");
// Only add the job to the queue if it is not at capacity
if (q->size < q->maxSize) {
Node * temp = (Node *) malloc(sizeof(Node));
temp->func = func;
temp->func_arg = arg;
temp->next = NULL;
q->totalAdded++;
// The first job added to the list
if (q->head == NULL) {
q->head = temp;
q->tail = temp;
q->head->prev = NULL;
} else {
q->tail->next = temp;
q->tail->next->prev = q->tail;
q->tail = temp;
}
// Increment the size of the queue
q->size++;
}
}
// Remove a job from the queue to be used by a threadpool
void removeJob(Queue * q, dispatch_fn * func, void ** arg) {
//fprintf(stdout,"removeJob\n");
// Only remove a job if there is at least one already on the queue
if (q->size > 0) {
Node * temp = q->head;
// Set these pointers in the thread to the values of the job info
*func = temp->func;
*arg = temp->func_arg;
// Remove the last job on the queue
if (q->head == q->tail) {
q->head = NULL;
q->tail = NULL;
free(temp); // delete the memory of this node
} else {
q->head = q->head->next;
q->head->prev = NULL;
free(temp); // delete the memory of this node
}
// Decrement the size of the queue
q->size--;
}
}
// Can another job be added to the queue
int canAddJob(struct Queue * q) {
//fprintf(stdout,"canAddJob\n");
return(q->size < q->maxSize);
}
// Is there a job to be done
int isJobAvailable(struct Queue * q) {
//fprintf(stdout,"isJobAvailable\n");
return(q->head != NULL);
}