-
Notifications
You must be signed in to change notification settings - Fork 0
/
list.c
120 lines (102 loc) · 2.61 KB
/
list.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
#include <pthread.h>
#include "list.h"
#include <stdlib.h>
#include <stdio.h>
list_t *list_init() {
list_t *list = calloc(1, sizeof(list_t));
if(pthread_mutex_init(&list->mutex, NULL) != 0) {
printf("Error creating mutex. \n");
exit(1);
}
return list;
}
void list_push(list_t *list, void *data) {
pthread_mutex_lock(&list->mutex);
node_t *element = calloc(1, sizeof(node_t));
element->data = data;
if (!list->head) {
list->head = element;
list->tail = element;
list->tail->next = element;
list->tail->previous = element;
list->head->next = element;
list->head->previous = element;
list->node_count += 1;
pthread_mutex_unlock(&list->mutex);
return;
}
list->tail->next = element;
element->previous = list->tail;
list->tail = element;
element->next = list->head;
list->head->previous = list->tail;
list->node_count += 1;
pthread_mutex_unlock(&list->mutex);
}
void *list_pop_front(list_t *list) {
if (list->head == NULL) {
return NULL;
}
pthread_mutex_lock(&list->mutex);
node_t *node = list->head;
node_t *next = list->head->next;
if(next == node) {
list->head = NULL;
list->tail = NULL;
goto end;
}
list->head = next;
list->tail->next = next;
next->previous = list->tail;
end:
list->node_count -= 1;
pthread_mutex_unlock(&list->mutex);
void *data = node->data;
free(node);
return data;
}
void *list_pop_back(list_t *list) {
if (list->tail == NULL) {
return NULL;
}
pthread_mutex_lock(&list->mutex);
node_t *node = list->tail;
node_t *previous = list->tail->previous;
if(previous == node) {
list->head = NULL;
list->tail = NULL;
goto end;
}
list->tail = previous;
list->head->previous = previous;
previous->next = list->head;
end:
list->node_count -= 1;
pthread_mutex_unlock(&list->mutex);
void *data = node->data;
free(node);
return data;
}
void _list_free(list_t *list, int with_data) {
node_t *node = list->head;
if (node) {
do {
node_t *to_free = node;
node = node->next;
if (with_data)
free(to_free->data);
free(to_free);
} while (node != list->head);
}
if(pthread_mutex_destroy(&list->mutex) != 0) {
printf("Error destroying mutex. \n");
exit(1);
}
free(list);
}
void list_free_without_data(list_t *list) {
_list_free(list, 0);
}
void list_free(list_t *list) {
_list_free(list, 1);
}