#include #include #include #include #include "LinkedList.h" LinkedList *newLL() { Element *e = NULL; LinkedList *l = malloc(sizeof(LinkedList)); assert(l != NULL); pthread_mutex_init(&(l->mutex),NULL); // In the list, we add two markers which will simplify add and // remove algorithms e = malloc(sizeof(Element)); assert(e != NULL); e->val = INT_MIN; l->first = e; e = malloc(sizeof(Element)); assert(e != NULL); e->val = INT_MAX; l->first->next = e; l->first->next->next = NULL; return l; } void dumpLL(LinkedList *l) { Element *e = NULL; printf("Begin dump LinkedList %p\n", l); MUTEX_LOCK(l->mutex); for (e = l->first->next; e->val != INT_MAX ; e = e->next) { printf(" val = %8d\n", e->val); } MUTEX_UNLOCK(l->mutex); printf("End dump LinkedList %p\n", l); } int sizeLL(LinkedList *l) { Element *e = NULL; int nb = 0; MUTEX_LOCK(l->mutex); for (e = l->first->next; e->val != INT_MAX ; e = e->next) { ++nb; } MUTEX_UNLOCK(l->mutex); return nb; } void freeLL(LinkedList *l) { Element *e = l->first; int rc; // We free all the elements inside the list do { Element *nextE = e->next; free(e); e = nextE; } while (e != NULL); // We free the LinkedList itself rc = pthread_mutex_destroy(&(l->mutex)); assert(rc == 0); free(l); } void addLL(LinkedList *l, int v) { Element *e = l->first; Element *newE = NULL; assert(v != INT_MIN && v!= INT_MAX); MUTEX_LOCK(l->mutex); // We look where to insert our value while (v > e->next->val) { e = e->next; } // We insert the new element in the list between e and e->next newE = malloc(sizeof(Element)); assert(newE != NULL); newE->val = v; newE->next = e->next; e->next = newE; MUTEX_UNLOCK(l->mutex); } void removeLL(LinkedList *l, int v) { Element *e = l->first; assert(v != INT_MIN && v!= INT_MAX); MUTEX_LOCK(l->mutex); // We look for the value to suppress while (v > e->next->val) { e = e->next; } if (v == e->next->val) { // The value we need to remove is contained in e->next Element *eToRemove = e->next; e->next = eToRemove->next; eToRemove->next = NULL; free(eToRemove); } else { fprintf(stderr, "WARNING : value %d not found in list %p\n", v, l); } MUTEX_UNLOCK(l->mutex); }