diff --git a/kernel/include/mutex.hpp b/kernel/include/mutex.hpp index ba7e465b..e511b133 100644 --- a/kernel/include/mutex.hpp +++ b/kernel/include/mutex.hpp @@ -8,23 +8,43 @@ #ifndef MUTEX_H #define MUTEX_H -#include "semaphore.hpp" +//TODO Ideally this should simply be a wrapper around a semaphore struct mutex { private: - semaphore sem; + spinlock lock; + volatile size_t value; + circular_buffer queue; public: void init(){ - sem.init(1); + value = 1; } void acquire(){ - sem.wait(); + std::lock_guard l(lock); + + if(value > 0){ + value = 0; + } else { + auto pid = scheduler::get_pid(); + queue.push(pid); + scheduler::block_process(pid); + } } void release(){ - sem.signal(); + std::lock_guard l(lock); + + if(queue.empty()){ + value = 1; + } else { + auto pid = queue.pop(); + scheduler::unblock_process(pid); + + //No need to increment value, the process won't + //decrement it + } } };