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