6af1087be1859a7755b70c6c2e32f398e01490cb
[lunaix-os.git] / lunaix-os / kernel / ds / mutex.c
1 #include <lunaix/ds/mutex.h>
2 #include <lunaix/process.h>
3
4 void
5 mutex_lock(mutex_t* mutex)
6 {
7     if (atomic_load(&mutex->lk) && mutex->owner == __current->pid) {
8         atomic_fetch_add(&mutex->lk, 1);
9         return;
10     }
11
12     while (atomic_load(&mutex->lk)) {
13         sched_yieldk();
14     }
15
16     atomic_fetch_add(&mutex->lk, 1);
17     mutex->owner = __current->pid;
18 }
19
20 void
21 mutex_unlock(mutex_t* mutex)
22 {
23     mutex_unlock_for(mutex, __current->pid);
24 }
25
26 void
27 mutex_unlock_for(mutex_t* mutex, pid_t pid)
28 {
29     if (mutex->owner != pid || !atomic_load(&mutex->lk)) {
30         return;
31     }
32     atomic_fetch_sub(&mutex->lk, 1);
33 }