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

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();
}