diff options
author | Jack Sangdahl <[email protected]> | 2024-10-03 11:45:34 -0600 |
---|---|---|
committer | Jack Sangdahl <[email protected]> | 2024-10-03 11:45:34 -0600 |
commit | 6e6f4151b7f709fbaf62e40479c700a81436512f (patch) | |
tree | d7bc4fd81a5ab9d163e6e94bb37058c6130eebd2 /pa4_shared_array/array.c | |
parent | eea3d410e709ebac4351f58487ed3c9f49631c44 (diff) | |
download | csci3753-6e6f4151b7f709fbaf62e40479c700a81436512f.tar.gz csci3753-6e6f4151b7f709fbaf62e40479c700a81436512f.zip |
pa4: improvements
Diffstat (limited to 'pa4_shared_array/array.c')
-rw-r--r-- | pa4_shared_array/array.c | 39 |
1 files changed, 10 insertions, 29 deletions
diff --git a/pa4_shared_array/array.c b/pa4_shared_array/array.c index 3a44566..dfda1b7 100644 --- a/pa4_shared_array/array.c +++ b/pa4_shared_array/array.c @@ -5,51 +5,32 @@ int array_init(array *s) { s->top = 0; - s->array = (char **)malloc(ARRAY_SIZE * sizeof(char *)); - for (int i = 0; i < ARRAY_SIZE; i++) - s->array[i] = (char *)malloc(MAX_NAME_LENGTH * sizeof(char)); sem_init(&s->mutex, 0, 1); - sem_init(&s->space, 0, ARRAY_SIZE); - sem_init(&s->items, 0, 0); + sem_init(&s->avail, 0, ARRAY_SIZE); + sem_init(&s->empty, 0, 0); return 0; } int array_put(array *s, char *hostname) { - if (s->top == ARRAY_SIZE - 1) { - printf("ERROR: stack full\n"); - return -1; - } - if (strlen(hostname) > MAX_NAME_LENGTH) { - printf("ERROR: %s size > %d\n", hostname, MAX_NAME_LENGTH); - return -1; - } - sem_wait(&s->space); + sem_wait(&s->avail); sem_wait(&s->mutex); - strcpy(s->array[s->top++], hostname); + s->data[s->top++] = hostname; sem_post(&s->mutex); - sem_post(&s->items); + sem_post(&s->empty); return 0; } int array_get(array *s, char **hostname) { - if (!s->top) { - printf("ERROR: stack empty\n"); - return -1; - } - sem_wait(&s->items); + sem_wait(&s->empty); sem_wait(&s->mutex); - *hostname = (char *)malloc(MAX_NAME_LENGTH * sizeof(char)); - strcpy(*hostname, s->array[--s->top]); + *hostname = s->data[--s->top]; sem_post(&s->mutex); - sem_post(&s->space); + sem_post(&s->avail); return 0; } void array_free(array *s) { - for (int i = 0; i < ARRAY_SIZE; i++) - free(s->array[i]); - free(s->array); sem_destroy(&s->mutex); - sem_destroy(&s->space); - sem_destroy(&s->items); + sem_destroy(&s->avail); + sem_destroy(&s->empty); } |