-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathqueue.c
More file actions
114 lines (94 loc) · 2.63 KB
/
queue.c
File metadata and controls
114 lines (94 loc) · 2.63 KB
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
#include <stdio.h>
#include "queue.h"
void queue_init(Queue *q) {
q->head = 0;
q->tail = 0;
q->count = 0;
}
int queue_empty(const Queue *q) {
return q->count == 0;
}
int queue_full(const Queue *q) {
return q->count == QUEUE_SIZE;
}
void queue_push(Queue *q, Process *proc) {
if (queue_full(q)) {
printf("Queue is full\n");
return;
}
q->processlist[q->tail] = proc;
q->tail = (q->tail + 1) % QUEUE_SIZE;
q->count++;
}
Process *queue_pop(Queue *q) {
if (queue_empty(q)) {
printf("Queue has No elements\n");
return NULL;
}
Process *proc = q->processlist[q->head];
q->head = (q->head + 1) % QUEUE_SIZE;
q->count--;
return proc;
}
int queue_remove(Queue *q, Process *proc) {
if (queue_empty(q)) return 0;
int removed = 0;
int idx = q->head;
for (int i = 0; i < q->count; i++) {
if (q->processlist[idx] == proc) { // proc 찾기
removed = 1;
}
if (removed && i != q->count - 1) { // 당기고
int next = (idx + 1) % QUEUE_SIZE;
q->processlist[idx] = q->processlist[next];
}
idx = (idx + 1) % QUEUE_SIZE;
}
if (removed == 0) return 0;
q->tail = (q->tail - 1 + QUEUE_SIZE) % QUEUE_SIZE;
q->count--;
return 1;
}
Process *queue_pop_shortest(Queue *q) {
if (queue_empty(q)) return NULL;
// 짧은거 찾고
int zz = q->head;
int idx = q->head;
for (int i = 1; i < q->count; i++) {
idx = (q->head + i) % QUEUE_SIZE;
if (q->processlist[idx]->remaining_time < q->processlist[zz]->remaining_time) {
zz = idx;
}
}
Process *selected = q->processlist[zz];
int cur = zz;
for (int i = 0; i < q->count - 1; i++) {
int next = (cur + 1) % QUEUE_SIZE;
q->processlist[cur] = q->processlist[next];
cur = next;
}
q->tail = (q->tail - 1 + QUEUE_SIZE) % QUEUE_SIZE;
q->count--;
return selected;
}
Process *queue_pop_highest_priority(Queue *q) {
if (queue_empty(q)) return NULL;
int zz = q->head;
int idx = q->head;
for (int i = 1; i < q->count; i++) {
idx = (q->head + i) % QUEUE_SIZE;
if (q->processlist[idx]->priority < q->processlist[zz]->priority) {
zz = idx;
}
}
Process *selected = q->processlist[zz];
int cur = zz;
for (int i = 0; i < q->count - 1; i++) {
int next = (cur + 1) % QUEUE_SIZE;
q->processlist[cur] = q->processlist[next];
cur = next;
}
q->tail = (q->tail - 1 + QUEUE_SIZE) % QUEUE_SIZE;
q->count--;
return selected;
}