1

implement semaphore

This commit is contained in:
2022-07-11 15:00:05 +02:00
parent be6aeb2b11
commit 012f68838b
4 changed files with 39 additions and 1 deletions

View File

@ -181,7 +181,6 @@ void Scheduler::block() {
}
cpu.disable_int();
Thread& next = *(Thread*)this->readyQueue.dequeue();
this->dispatch(next);
}

32
c_os/lib/Semaphore.cc Normal file
View File

@ -0,0 +1,32 @@
#include "Semaphore.h"
#include "kernel/Globals.h"
void Semaphore::p() {
// Lock to allow deterministic operations on counter
this->lock.acquire();
if (this->counter > 0) {
// Semaphore can be acquired
this->counter = this->counter - 1;
} else {
// Block and manage thread in semaphore queue until it's woken up by v()
this->waitQueue.enqueue(scheduler.get_active());
scheduler.block();
}
this->lock.release();
}
void Semaphore::v() {
this->lock.acquire();
if (!this->waitQueue.isEmpty()) {
// Semaphore stays busy and unblocks next thread to work in critical section
scheduler.deblock((Thread*)this->waitQueue.dequeue());
} else {
// No more threads want to work so free semaphore
this->counter = this->counter + 1;
}
this->lock.release();
}

View File

@ -50,6 +50,8 @@ static inline unsigned long CAS(unsigned long* ptr, unsigned long old, unsigned
* Beschreibung: Lock belegen. *
*****************************************************************************/
void SpinLock::acquire() {
// If lock == 0 the SpinLock can be aquired without waiting
// If lock == 1 the while loop blocks until aquired
while (CAS(ptr, 0, 1) != 0) {}
}

View File

@ -84,6 +84,11 @@ int main() {
scheduler.schedule();
// TODO: Use templates for queue so threads don't have to be casted down from chain
// TODO: Change scheduler to only use references instead of pointers
// TODO: Rewrite all demos to threads
// TODO: Make menu for demos
// TODO: Unify debug output format
// TODO: Serial output
// Scheduler doesn't return
return 0;