aboutsummaryrefslogtreecommitdiff
path: root/kernel/lib/mutex.c
diff options
context:
space:
mode:
Diffstat (limited to 'kernel/lib/mutex.c')
-rw-r--r--kernel/lib/mutex.c27
1 files changed, 27 insertions, 0 deletions
diff --git a/kernel/lib/mutex.c b/kernel/lib/mutex.c
new file mode 100644
index 0000000..cda8049
--- /dev/null
+++ b/kernel/lib/mutex.c
@@ -0,0 +1,27 @@
+#include <mutex.h>
+
+/* Internal use only. This function is atomic, meaning it cannot be interrupted by a system task switch. */
+static uint32_t atomic_exchange(uint32_t* ptr, uint32_t newval) {
+ uint32_t r;
+ asm volatile("xchg (%%ecx), %%eax" : "=a"(r) : "c"(ptr), "a"(newval));
+ return r;
+}
+
+void mutex_lock(uint32_t* mutex) {
+ while (atomic_exchange(mutex, MUTEX_LOCKED) == MUTEX_LOCKED) {
+ yield();
+ }
+}
+
+int mutex_try_lock(uint32_t* mutex) {
+ if (atomic_exchange(mutex, MUTEX_LOCKED) == MUTEX_LOCKED) {
+ return 0;
+ }
+ return 1;
+}
+
+void mutex_unlock(uint32_t* mutex) {
+ *mutex = MUTEX_UNLOCKED;
+}
+
+/* vim: set ts=4 sw=4 tw=0 noet :*/