From 05f5ad82dcbf43f32ca1f60eefa904d3229d1229 Mon Sep 17 00:00:00 2001 From: Akemi Izuko Date: Tue, 15 Oct 2024 19:47:18 -0600 Subject: [PATCH] Lab6: start semaphore example --- lab6/demos/semaphore_1_mutex.c | 84 ++++++++++++++++++++++++++++++++++ 1 file changed, 84 insertions(+) create mode 100644 lab6/demos/semaphore_1_mutex.c diff --git a/lab6/demos/semaphore_1_mutex.c b/lab6/demos/semaphore_1_mutex.c new file mode 100644 index 0000000..f04593e --- /dev/null +++ b/lab6/demos/semaphore_1_mutex.c @@ -0,0 +1,84 @@ +#include +#include +#include +#include +#include + +#define EMPTY -100 + +struct args { + sem_t buf_sem; + int* buffer; + int buf_length; + pthread_mutex_t buf_lock; +}; + +void put(struct args* a, int item) { + pthread_mutex_lock(&a->buf_lock); + a->buf_length += 1; + a->buffer = reallocarray(a->buffer, a->buf_length, sizeof(int)); + a->buffer[a->buf_length - 1] = item; + pthread_mutex_unlock(&a->buf_lock); +} + +int get(struct args* a) { + int item; + pthread_mutex_lock(&a->buf_lock); + + if (a->buf_length > 0) { + item = EMPTY; + } else { + item = a->buffer[0]; + a->buf_length -= 1; + a->buffer += 1; + } + + pthread_mutex_unlock(&a->buf_lock); + return item; +} + +void *producer(void *arg) { + struct args* a = arg; + + for (int i = 0; i < 100; i++) { + put(a, i); + sem_post(&a->buf_sem); + } + sleep(10); + + for (int i = 0; i < 100; i++) { + put(a, i); + sem_post(&a->buf_sem); + } + return NULL; +} + +void* consumer(void* arg) { + struct args* a = arg; + + while (1) { + sem_wait(&a->buf_sem); + int tmp = get(a); + printf("%d\n", tmp); + } + + return NULL; +} + +struct args* make_args() { + struct args* a = malloc(sizeof(struct args)); + sem_init(&a->buf_sem, 0, 1); + pthread_mutex_init(&a->buf_lock, NULL); + + a->buffer = calloc(0, sizeof(int)); + a->buf_length = 0; + + return a; +} + +int main(void) { + struct args* a = make_args(); + + pthread_t p1, p2, p3; + +}