-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsync_queue.c
More file actions
111 lines (106 loc) · 2.62 KB
/
sync_queue.c
File metadata and controls
111 lines (106 loc) · 2.62 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
#include "sync_queue.h"
#include <pthread.h>
#include <stdlib.h>
#include <errno.h>
#include <stdio.h>
sync_queue *sync_q_create() {
sync_queue *q = malloc(sizeof(sync_queue));
q->entries = 0;
q->front = 0;
q->rear = 0;
pthread_mutex_init(&q->lock, NULL);
return q;
}
/** assumes that the queue has been completely emptied*/
int sync_q_destroy(sync_queue *q) {
int mutex_status = 0;
mutex_status = pthread_mutex_destroy(&q->lock);
if (mutex_status != 0) {
perror("ERROR!!!");
exit(EXIT_FAILURE);
}
free(q);
return EXIT_SUCCESS;
}
int sync_q_empty(sync_queue *q) {
int mutex_status = 0;
mutex_status = pthread_mutex_lock(&q->lock);
if (mutex_status != 0) {
perror("ERROR!!!");
exit(EXIT_FAILURE);
}
int no_entries = q->entries;
mutex_status = pthread_mutex_unlock(&q->lock);
if (mutex_status != 0) {
perror("ERROR!!!");
exit(EXIT_FAILURE);
}
if (no_entries == 0) {
return 1;
} else {
return 0;
}
}
int sync_q_add(sync_queue *q, char *name) {
int mutex_status = 0;
mutex_status = pthread_mutex_lock(&q->lock);
if (mutex_status != 0) {
perror("ERROR!!!");
exit(EXIT_FAILURE);
}
queue_node *entry = malloc(sizeof(queue_node));
if (!entry) {
mutex_status = pthread_mutex_unlock(&q->lock);
if (mutex_status != 0) {
perror("ERROR!!!");
exit(EXIT_FAILURE);
}
return EXIT_FAILURE;
}
entry->name = name;
entry->next = 0;
if (q->entries == 0) {
q->front = entry;
q->rear = entry;
}
else {
q->rear->next = entry;
q->rear = entry;
}
q->entries += 1;
mutex_status = pthread_mutex_unlock(&q->lock);
if (mutex_status != 0) {
perror("ERROR!!!");
exit(EXIT_FAILURE);
}
return EXIT_SUCCESS;
}
queue_node *sync_q_remove(sync_queue *q) {
int mutex_status = 0;
mutex_status = pthread_mutex_lock(&q->lock);
if (mutex_status != 0) {
perror("ERROR!!!");
exit(EXIT_FAILURE);
}
if (q->entries == 0) {
mutex_status = pthread_mutex_unlock(&q->lock);
if (mutex_status != 0) {
perror("ERROR!!!");
exit(EXIT_FAILURE);
}
return 0;
}
queue_node *entry = q->front;
q->front = q->front->next;
q->entries -= 1;
/** removed the last node */
if (q->entries == 0) {
q->rear = 0;
}
mutex_status = pthread_mutex_unlock(&q->lock);
if (mutex_status != 0) {
perror("ERROR!!!");
exit(EXIT_FAILURE);
}
return entry;
}