diff --git a/mutex_barriers/ex3/Ex3_etu.c b/mutex_barriers/ex3/Ex3_etu.c index 9c12921819f02b3b0111891e6d6bd1de1d9b8f20..7977829ee9667ecea58e75cc92a3f677fe35403f 100644 --- a/mutex_barriers/ex3/Ex3_etu.c +++ b/mutex_barriers/ex3/Ex3_etu.c @@ -1,5 +1,5 @@ #include "thread_wrapper.h" -// #include <assert.h> +#include <assert.h> #include <pthread.h> #include <stdbool.h> #include <stdio.h> @@ -20,7 +20,7 @@ typedef struct { int *ptr; int size; int capacity; - pthread_mutex_t lock; + pthread_mutex_t *lock; } stack_t; typedef struct { @@ -29,20 +29,14 @@ typedef struct { } thr_params; bool stack_create(stack_t *s, int max_size) { - if (max_size < 1) { - fprintf(stderr, "Stack size has to be equal to or greater than 1"); - return false; - } - - pthread_mutexattr_t attr; - pthread_mutexattr_init(&attr); - pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_ERRORCHECK); + assert(max_size >= 1); - pthread_mutex_init(&s->lock, &attr); - - // pthread_mutexattr_destroy(&attr); + s->lock = mutex_create(); + assert(s->lock != NULL); s->ptr = malloc(max_size * sizeof(int)); + assert(s->ptr != NULL); + s->capacity = max_size; s->size = 0; @@ -53,11 +47,10 @@ bool stack_is_empty(stack_t *s) { return s->size == 0; } void stack_push(stack_t *s, int val) { if (s->size < s->capacity) { - pthread_mutex_lock(&s->lock); + mutex_lock(s->lock); s->ptr[(s->capacity - 1) - s->size] = val; s->size++; - pthread_mutex_unlock(&s->lock); - // fprintf(stderr, "%d has been inserted\n", val); + mutex_unlock(s->lock); } else { fprintf(stderr, "Stack is full\n"); } @@ -65,28 +58,28 @@ void stack_push(stack_t *s, int val) { // Returns -1 in case of an error int stack_pop(stack_t *s) { - if (stack_is_empty(s)) { - fprintf(stderr, "Stack is empty\n"); - return -1; - } + assert(!stack_is_empty(s)); - pthread_mutex_lock(&s->lock); + // pthread_mutex_lock(&s->lock); + mutex_lock(s->lock); int ret = s->ptr[s->capacity - s->size]; s->size--; - pthread_mutex_unlock(&s->lock); + mutex_unlock(s->lock); return ret; } void stack_destroy(stack_t *s) { - if (s->ptr != NULL) { - pthread_mutex_destroy(&s->lock); - free(s->ptr); - } + mutex_destroy(s->lock); + + assert(s->ptr != NULL); + free(s->ptr); } void *test_stack(void *data) { + fprintf(stderr, "thread n°%lu, waiting...\n", pthread_self()); bar_wait(b); + fprintf(stderr, "launching task for thread id n°%lu\n", pthread_self()); thr_params *p = (thr_params *)data;