aboutsummaryrefslogtreecommitdiff
path: root/Src/nu/simple_rwlock.h
diff options
context:
space:
mode:
authorJean-Francois Mauguit <jfmauguit@mac.com>2024-09-24 09:03:25 -0400
committerGitHub <noreply@github.com>2024-09-24 09:03:25 -0400
commitbab614c421ed7ae329d26bf028c4a3b1d2450f5a (patch)
tree12f17f78986871dd2cfb0a56e5e93b545c1ae0d0 /Src/nu/simple_rwlock.h
parent4bde6044fddf053f31795b9eaccdd2a5a527d21f (diff)
parent20d28e80a5c861a9d5f449ea911ab75b4f37ad0d (diff)
downloadwinamp-bab614c421ed7ae329d26bf028c4a3b1d2450f5a.tar.gz
Merge pull request #5 from WinampDesktop/community
Merge to main
Diffstat (limited to 'Src/nu/simple_rwlock.h')
-rw-r--r--Src/nu/simple_rwlock.h49
1 files changed, 49 insertions, 0 deletions
diff --git a/Src/nu/simple_rwlock.h b/Src/nu/simple_rwlock.h
new file mode 100644
index 00000000..f9952959
--- /dev/null
+++ b/Src/nu/simple_rwlock.h
@@ -0,0 +1,49 @@
+#pragma once
+
+/*
+Simple Reader/Writer lock. Lets unlimited readers through but a writer will lock exclusively
+not meant for high-throughput uses
+this is useful when writes are very infrequent
+*/
+#include <bfc/platform/types.h>
+#include <windows.h>
+
+typedef size_t simple_rwlock_t;
+static const size_t simple_rwlock_writer_active = 1; // writer active flag
+static const size_t simple_rwlock_reader_increment= 2; // to adjust reader count
+
+static inline void simple_rwlock_write_lock(simple_rwlock_t *lock)
+{
+ while (InterlockedCompareExchangePointer((PVOID volatile*)lock, (PVOID)simple_rwlock_writer_active, 0))
+ {
+ // nop
+ }
+}
+
+static inline void simple_rwlock_write_unlock(simple_rwlock_t *lock)
+{
+#ifdef _WIN64
+ InterlockedExchangeAdd64((LONGLONG volatile*)lock, -simple_rwlock_writer_active);
+#else
+ InterlockedExchangeAdd((LONG volatile*)lock, -simple_rwlock_writer_active);
+#endif
+}
+
+
+static inline void simple_rwlock_read_lock(simple_rwlock_t *lock)
+{
+ InterlockedExchangeAdd((LONG volatile*)lock, simple_rwlock_reader_increment);
+ while ((*lock & simple_rwlock_writer_active))
+ {
+ // nope
+ }
+}
+
+static inline void simple_rwlock_read_unlock(simple_rwlock_t *lock)
+{
+ #ifdef _WIN64
+ InterlockedExchangeAdd64((LONGLONG volatile*)lock, -simple_rwlock_reader_increment);
+#else
+ InterlockedExchangeAdd((LONG volatile*)lock, -simple_rwlock_reader_increment);
+#endif
+}