Support to multi-threading and pthread interface (POSIX.1-2008) (#23)
[lunaix-os.git] / lunaix-os / kernel / ds / mutex.c
index 7bfbf10620fe0b8bd6c453d67ddbff00b23b7052..fd14df5042800aa55a4b14b15cecceed245bf1a3 100644 (file)
@@ -1,10 +1,20 @@
 #include <lunaix/ds/mutex.h>
 #include <lunaix/process.h>
+#include <lunaix/sched.h>
 
 void
 mutex_lock(mutex_t* mutex)
 {
-    sem_wait(&mutex->sem);
+    if (atomic_load(&mutex->lk) && mutex->owner == __current->pid) {
+        atomic_fetch_add(&mutex->lk, 1);
+        return;
+    }
+
+    while (atomic_load(&mutex->lk)) {
+        sched_pass();
+    }
+
+    atomic_fetch_add(&mutex->lk, 1);
     mutex->owner = __current->pid;
 }
 
@@ -17,8 +27,8 @@ mutex_unlock(mutex_t* mutex)
 void
 mutex_unlock_for(mutex_t* mutex, pid_t pid)
 {
-    if (mutex->owner != pid) {
+    if (mutex->owner != pid || !atomic_load(&mutex->lk)) {
         return;
     }
-    sem_post(&mutex->sem);
+    atomic_fetch_sub(&mutex->lk, 1);
 }
\ No newline at end of file