mirror of
https://github.com/wichtounet/thor-os.git
synced 2025-09-09 04:22:04 -04:00
Simplify mutex
This commit is contained in:
parent
1ea3f90f4e
commit
03c060af34
@ -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<scheduler::pid_t, 16> queue;
|
||||
|
||||
public:
|
||||
void init(){
|
||||
sem.init(1);
|
||||
value = 1;
|
||||
}
|
||||
|
||||
void acquire(){
|
||||
sem.wait();
|
||||
std::lock_guard<spinlock> 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<spinlock> 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
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
|
Loading…
x
Reference in New Issue
Block a user