Simplify mutex

This commit is contained in:
Baptiste Wicht 2016-06-30 21:01:11 +02:00
parent 1ea3f90f4e
commit 03c060af34

View File

@ -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
}
}
};