#include #include #include #include typedef int element_t; struct list { struct node { struct node *next, *previous; element_t e; } * head, *tail; }; void list_init(struct list *l) { l->head = l->tail = NULL; } struct node *list_add_back(struct list *l, element_t e) { struct node *newNode = malloc(sizeof(struct node)); newNode->next = 0; newNode->e = e; if (l->tail == NULL) { newNode->previous = NULL; l->head = l->tail = newNode; } else { newNode->previous = l->tail; l->tail->next = newNode; l->tail = newNode; } return newNode; } void list_delete_node(struct list *l, struct node *n) { if (n->previous == NULL) l->head = n->next; else n->previous->next = n->next; if (n->next == NULL) l->tail = n->previous; else n->next->previous = n->previous; free(n); } void list_delete_value(struct list *l, element_t e) { struct node *n = l->head, *next; while (n != NULL) { next = n->next; if (n->e == e) list_delete_node(l, n); n = next; } } void list_print(struct list *l, int reverse) { struct node *n = reverse ? l->tail : l->head; while (n != NULL) { printf("%d\n", n->e); n = reverse ? n->previous : n->next; } } void *adder(void *arg) { struct list *l = (struct list *)arg; srand(time(0)); while (1) { list_add_back(l, rand() % 25); usleep(10); } } void *remover(void *arg) { struct list *l = (struct list *)arg; srand(time(0) + 2); while (1) { list_delete_value(l, rand() % 25); usleep(5); } } int main() { struct list l; list_init(&l); pthread_t a, r; pthread_create(&a, NULL, adder, &l); pthread_create(&r, NULL, remover, &l); pthread_detach(a); pthread_detach(r); while (getchar() != EOF) list_print(&l, 0); return 0; }