From 200f22578700b82c5a2d2052c9fda0d9e431d25f Mon Sep 17 00:00:00 2001 From: Stefan Zabka Date: Fri, 12 Jun 2020 00:05:28 +0200 Subject: THIS SHIT WORKS --- 04_exercise/rwlock/rwlock.c | 67 +++++++++++++++++++++++++++++++++++++++++++++ 04_exercise/rwlock/rwlock.h | 16 +++++++++++ 2 files changed, 83 insertions(+) create mode 100644 04_exercise/rwlock/rwlock.c create mode 100644 04_exercise/rwlock/rwlock.h (limited to '04_exercise/rwlock') diff --git a/04_exercise/rwlock/rwlock.c b/04_exercise/rwlock/rwlock.c new file mode 100644 index 0000000..3de5083 --- /dev/null +++ b/04_exercise/rwlock/rwlock.c @@ -0,0 +1,67 @@ +// +// Created by stefan on 11.06.20. +// + +#include "rwlock.h" +#include +#include +#include +#include + +static const bool DEBUG = false; + + +void rwLockWrite(atomic_char *lock) { + char status; + bool succeeded; + do { + status = RW_UNLOCKED; + succeeded = atomic_compare_exchange_weak(lock, &status, RW_WRITE_LOCKED); + } while (!succeeded); + if(DEBUG) { + fprintf(stderr, "Thread %lu: Aquired Write Lock \n", pthread_self() % 1000); + } + +} + +void rwUnlockWrite(atomic_char *lock) { + char expected = RW_WRITE_LOCKED; + if (!atomic_compare_exchange_strong(lock, &expected, RW_UNLOCKED)) { + fprintf(stderr, "Couldn't unlock from writelock. Lock was at %d", expected); + perror("Lock got into undefined state"); + exit(-1); + } + if(DEBUG) { + fprintf(stderr, "Thread %lu: Released Write Lock \n", pthread_self() % 1000); + } + if (sched_yield() < 0) { + perror("Couldn't sleep. This shouldn't happen."); + exit(-1); + } + +} +void rwLockRead(atomic_char *lock) { + while (atomic_load(lock) == RW_WRITE_LOCKED) { + + } + atomic_fetch_add(lock, 1); + if(DEBUG) { + fprintf(stderr, "Thread %lu: Aquired Read Lock \n", pthread_self() % 1000); + } +} +void rwUnlockRead(atomic_char *lock) { + char value = atomic_load(lock); + if (value < 1) { + fprintf(stderr, "Couldn't unlock from readlock. Lock was at %d", value); + perror("Lock got into undefined state"); + exit(-1); + } + atomic_fetch_sub(lock, 1); + if(DEBUG) { + fprintf(stderr, "Thread %lu: Released Read Lock \n", pthread_self() % 1000); + } + if (sched_yield() < 0) { + perror("Couldn't sleep. This shouldn't happen."); + exit(-1); + } +} \ No newline at end of file diff --git a/04_exercise/rwlock/rwlock.h b/04_exercise/rwlock/rwlock.h new file mode 100644 index 0000000..aa27f09 --- /dev/null +++ b/04_exercise/rwlock/rwlock.h @@ -0,0 +1,16 @@ +// +// Created by stefan on 11.06.20. +// + +#ifndef BETRIEBSYSTEME_RWLOCK_H +#define BETRIEBSYSTEME_RWLOCK_H +#include + +static const char RW_WRITE_LOCKED = -1; +static const char RW_UNLOCKED = 0; +void rwLockWrite(atomic_char *lock); +void rwUnlockWrite(atomic_char *lock); +void rwLockRead(atomic_char *lock); +void rwUnlockRead(atomic_char *lock); + +#endif // BETRIEBSYSTEME_RWLOCK_H -- cgit v1.2.3-54-g00ecf